package com.ziyun.pop.modules.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pay.api.WeixinpayService;
import com.pay.constant.PayResult;
import com.pay.event.WeixinpayCallBackEvent;
import com.service.common.constant.GoodsSplitType;
import com.service.common.constant.OrderSplitType;
import com.service.common.constant.SplitProcessType;
import com.service.common.model.PageResult;
import com.service.goods.constant.GoodsResult;
import com.service.goods.model.goods.BaseGoodsInfoVO;
import com.service.goods.model.goods.MultyErpOrderParam;
import com.service.order.api.MallErpOrderService;
import com.service.order.api.OrderService;
import com.service.order.constant.OrderResult;
import com.service.order.constant.PayStatus;
import com.service.order.constant.PayType;
import com.service.order.exception.OrderException;
import com.service.order.model.address.AddressResultDto;
import com.service.order.model.erp.AllotOrderResultDto;
import com.service.order.model.erp.AllotProductParamDto;
import com.service.order.model.erp.ErpAllotFactoryOrderParamDto;
import com.service.order.model.erp.OldItemNew;
import com.service.order.model.order.OrderCancelBatchParamDto;
import com.service.order.model.order.OrderMessageParamDto;
import com.service.order.model.order.OrderMessageVO;
import com.service.pay.conf.weixinpaySdk.HttpXmlUtils;
import com.service.pay.conf.weixinpaySdk.JdomParseXmlUtils;
import com.service.pay.conf.weixinpaySdk.WXSignUtils;
import com.service.pay.conf.weixinpaySdk.WxPayConfig;
import com.service.quote.module.factory.model.FactoryQuoteInfo;
import com.utility.New;
import com.ziyun.pop.common.e.DeleteEnum;
import com.ziyun.pop.common.e.logistics.LogisticsSendTypeEnum;
import com.ziyun.pop.common.e.mercharReport.ProductionStatus;
import com.ziyun.pop.common.e.order.*;
import com.ziyun.pop.common.e.production.*;
import com.ziyun.pop.common.e.quoteAttribute.QuoteAttributeValueEnum;
import com.ziyun.pop.common.e.storeMember.MerchantsTypeEnum;
import com.ziyun.pop.common.utils.*;
import com.ziyun.pop.modules.erpOrderLog.entity.ErpOrderLogEntity;
import com.ziyun.pop.modules.erpOrderLog.service.ErpOrderLogService;
import com.ziyun.pop.modules.erpSupplierOffline.entity.ErpSupplierOfflineEntity;
import com.ziyun.pop.modules.erpSupplierOffline.service.ErpSupplierOfflineService;
import com.ziyun.pop.modules.freightages.entity.SdbEctoolsRegionsEntity;
import com.ziyun.pop.modules.freightages.service.SdbEctoolsRegionsService;
import com.ziyun.pop.modules.goods.entity.GoodsEntity;
import com.ziyun.pop.modules.goods.service.GoodsService;
import com.ziyun.pop.modules.goods.vo.GoodsInfoVo;
import com.ziyun.pop.modules.goodsCategory.entity.GoodsCategoryEntity;
import com.ziyun.pop.modules.goodsCategory.service.GoodsCategoryService;
import com.ziyun.pop.modules.goodsProduct.entity.GoodsProductEntity;
import com.ziyun.pop.modules.goodsProduct.service.GoodsProductService;
import com.ziyun.pop.modules.logistics.dto.ErpLogisticsDto;
import com.ziyun.pop.modules.logistics.entity.ErpLogisticsEntity;
import com.ziyun.pop.modules.logistics.entity.ErpLogisticsItemEntity;
import com.ziyun.pop.modules.logistics.service.ErpLogisticsItemService;
import com.ziyun.pop.modules.logistics.service.ErpLogisticsService;
import com.ziyun.pop.modules.logistics.service.LogisticsTypeService;
import com.ziyun.pop.modules.order.dao.ErpOrderDao;
import com.ziyun.pop.modules.order.dto.*;
import com.ziyun.pop.modules.order.entity.*;
import com.ziyun.pop.modules.order.operate.ErpOrderStateContext;
import com.ziyun.pop.modules.order.service.*;
import com.ziyun.pop.modules.order.utils.UserPaymentUtils;
import com.ziyun.pop.modules.order.vo.OrderCraftServerVo;
import com.ziyun.pop.modules.order.vo.QuoteAllotCraftsVo;
import com.ziyun.pop.modules.orderRemarks.service.OrderRemarksService;
import com.ziyun.pop.modules.production.entity.ErpOrderItemEntity;
import com.ziyun.pop.modules.production.entity.ErpOrderProductionEntity;
import com.ziyun.pop.modules.production.service.ErpOrderItemService;
import com.ziyun.pop.modules.production.service.ErpOrderProductionService;
import com.ziyun.pop.modules.production.vo.ErpOrderProductionListVo;
import com.ziyun.pop.modules.quoteParts.entity.QuotePartsEntity;
import com.ziyun.pop.modules.quoteParts.service.QuotePartsService;
import com.ziyun.pop.modules.quoteProductBaseInfo.service.QuoteProductBaseInfoService;
import com.ziyun.pop.modules.storeFavouredPrice.entity.StoreFavouredPriceDetailEntity;
import com.ziyun.pop.modules.storeFavouredPrice.entity.StoreFavouredPriceEntity;
import com.ziyun.pop.modules.storeFavouredPrice.service.StoreFavouredPriceDetailService;
import com.ziyun.pop.modules.storeFavouredPrice.service.StoreFavouredPriceService;
import com.ziyun.pop.modules.storeGoodsCategory.entity.StoreGoodsCategoryEntity;
import com.ziyun.pop.modules.storeGoodsCategory.service.StoreGoodsCategoryService;
import com.ziyun.pop.modules.storeGoodsProduct.entity.StoreGoodsProductEntity;
import com.ziyun.pop.modules.storeGoodsProduct.service.StoreGoodsProductService;
import com.ziyun.pop.modules.storeMember.entity.StoreMemberEntity;
import com.ziyun.pop.modules.storeMember.entity.UserBaseInfoEntity;
import com.ziyun.pop.modules.storeMember.service.StoreMemberService;
import com.ziyun.pop.modules.storeMember.service.UserBaseInfoService;
import com.ziyun.pop.modules.storeMember.vo.StoreMemberEntityVo;
import com.ziyun.pop.modules.storeProductPrice.entity.StoreProductPriceEntity;
import com.ziyun.pop.modules.storeProductPrice.service.StoreProductPriceService;
import com.ziyun.pop.modules.supp.entity.SellerInfoEntity;
import com.ziyun.pop.modules.supp.service.SellerInfoService;
import com.ziyun.pop.modules.userAdvance.entity.UserAdvanceEntity;
import com.ziyun.pop.modules.userAdvance.service.UserAdvanceService;
import com.ziyun.pop.modules.userPayment.service.UserPaymentService;
import com.ziyun.pop.modules.userPaymentBill.entity.UserPaymentBillEntity;
import com.ziyun.pop.modules.userPaymentBill.service.UserPaymentBillService;
import com.ziyun.pop.modules.userWallet.entity.UserWalletEntity;
import com.ziyun.pop.modules.userWallet.service.UserWalletService;
import io.renren.common.exception.RRException;
import io.renren.common.utils.DateUtils;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.common.utils.R;
import io.renren.common.validator.ValidatorUtils;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.service.SysUserService;
import net.sf.json.JSONArray;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


@Service("erpOrderService")
public class ErpOrderServiceImpl extends ServiceImpl<ErpOrderDao, ErpOrderEntity> implements ErpOrderService {

    private static Logger logger = LoggerFactory.getLogger(ErpOrderServiceImpl.class);

    private static Long ZIYUN_SELLER_ID = 1L;

    private static Long ZIYUN_FACTORY_ID = 20L;

    @Autowired
    private ErpOrderItemService erpOrderItemService;

    @Autowired
    private UserPaymentService userPaymentService;

    @Autowired
    private UserWalletService userWalletService;

    @Autowired
    private UserPaymentBillService userPaymentBillService;

    @Autowired
    private ErpOrderLogService erpOrderLogService;

    @Autowired
    private ErpLogisticsService erpLogisticsService;

    @Autowired
    private ErpLogisticsItemService erpLogisticsItemService;

    @Autowired
    private StoreMemberService storeMemberService;

    @Autowired
    private UserBaseInfoService userBaseInfoService;

    @Autowired
    private StoreFavouredPriceService storeFavouredPriceService;

    @Autowired
    private StoreFavouredPriceDetailService storeFavouredPriceDetailService;

    @Autowired
    private StoreProductPriceService storeProductPriceService;

    @Autowired
    private StoreGoodsProductService storeGoodsProductService;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private ErpOrderProductionService erpOrderProductionService;

    @Autowired
    private ErpOrderAllotRelevanceService erpOrderAllotRelevanceService;

    @Autowired
    private SellerInfoService sellerInfoService;

    @Autowired
    private QuotePartsService quotePartsService;

    @Autowired
    private GoodsCategoryService goodsCategoryService;

    @Autowired
    private OrderRemarksService orderRemarksService;

    @Autowired
    private ErpSupplierOfflineService erpSupplierOfflineService;

    @Autowired
    private QuoteProductBaseInfoService quoteProductBaseInfoService;

    @Autowired
    private com.service.goods.api.GoodsService goodsAlloteService;

    @Autowired
    private MallErpOrderService mallErpOrderService;

    @Autowired
    private OrderService microOrderService;

    @Autowired
    ApplicationContext applicationContext;

    @Autowired
    WxPayConfig wxPayConfig;

    @Autowired
    private StoreGoodsCategoryService storeGoodsCategoryService;

    @Autowired
    private GoodsProductService goodsProductService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private LogisticsTypeService logisticsTypeService;

    @Autowired
    private SdbEctoolsRegionsService sdbEctoolsRegionsService;

    @Autowired
    private UserAccessoryService userAccessoryService;

    @Autowired
    private OrderTaxService orderTaxService;

    @Autowired
    private UserAdvanceService userAdvanceService;

    @Autowired
    private WeixinpayService weixinpayService;

    @Autowired
    private BatchOrderPaymentService batchOrderPaymentService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        Page<ErpOrderEntity> page = (Page<ErpOrderEntity>) this.page(
                new Query<ErpOrderEntity>(params).getPage(),
                new QueryWrapper<ErpOrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageErpOrderList(Map<String, Object> params) {

        Page<ErpOrderEntity> page = new Page<>(Integer.parseInt(params.get("page").toString()), Integer.parseInt(params.get("limit").toString()));
        page.setRecords(this.baseMapper.queryPageErpOrderList(page, params));
        return new PageUtils(page);
    }

    @Override
    public List<String> querySalesManList(Long sellerId) {
        return this.baseMapper.querySalesManList(sellerId);
    }

    @Override
    public List<String> queryRegionsSascade() {
        return this.baseMapper.queryRegionsSascade();
    }


    @Override
    public boolean updateByMap(Map<String, Object> map, String orderNo) {
        int update = this.baseMapper.updateByMap(map, orderNo);
        if (update > 0) {
            return true;
        }
        return false;
    }

    @Override
    public R queryPageMonthlyOrderList(Map<String, Object> params) {
        String orderNo = (String) params.get("orderNo");
        String memberName = (String) params.get("memberName");
        String productionStatus = (String) params.get("productionStatus");
        String payStatus = (String) params.get("payStatus");
        String beginCreatetime = (String) params.get("beginCreatetime");
        String endCreatetime = (String) params.get("endCreatetime");
        Long supplierId = (Long) params.get("supplierId");
        Integer onCredit = (Integer) params.get("onCredit");

        Page<ErpOrderEntity> page = (Page<ErpOrderEntity>) this.page(
                new Query<ErpOrderEntity>(params).getPage(),
                new QueryWrapper<ErpOrderEntity>()
                        .eq("third_merchant_id", supplierId)
                        .eq("on_credit", onCredit)
                        .like(StringUtils.isNotBlank(orderNo), "order_no", orderNo)
                        .like(StringUtils.isNotBlank(memberName), "member_name", memberName)
                        .eq(StringUtils.isNotBlank(productionStatus), "production_status", productionStatus)
                        .eq(StringUtils.isNotBlank(payStatus), "pay_status", payStatus)
                        .ge(StringUtils.isNotBlank(beginCreatetime), "order_createtime", beginCreatetime)
                        .le(StringUtils.isNotBlank(endCreatetime), "order_createtime", endCreatetime)
                        .notIn("production_status", ProductionStatusEnum.CANCELLED.toInt())
                        .orderBy(true, false, "create_time")
        );

        // 应付总额
        List<ErpOrderEntity> records = page.getRecords();
        BigDecimal totalAmount = records.stream()
                .map(ErpOrderEntity::getPayableAmount)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        Map<String, Object> userData = new HashMap<>();
        //当前页总额
        userData.put("totalAmount", totalAmount);
        //根据筛选条件得到总额
        List<ErpOrderEntity> list = this.list(new QueryWrapper<ErpOrderEntity>()
                .eq("third_merchant_id", supplierId)
                .eq("on_credit", onCredit)
                .like(StringUtils.isNotBlank(orderNo), "order_no", orderNo)
                .like(StringUtils.isNotBlank(memberName), "member_name", memberName)
                .eq(StringUtils.isNotBlank(productionStatus), "production_status", productionStatus)
                .eq(StringUtils.isNotBlank(payStatus), "pay_status", payStatus)
                .ge(StringUtils.isNotBlank(beginCreatetime), "order_createtime", beginCreatetime)
                .le(StringUtils.isNotBlank(endCreatetime), "order_createtime", endCreatetime)
                .notIn("production_status", ProductionStatusEnum.CANCELLED.toInt()));
        BigDecimal allTotalAmount = list.stream()
                .map(ErpOrderEntity::getPayableAmount)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        // 枚举参数
        userData.put("productionStatusEnum", JsonUtils.enumToList(ProductionStatusEnum.class));
        userData.put("allTotalAmount",allTotalAmount);
        return R.ok().put("page", new PageUtils(page))
                .put("userData", userData);
    }

    /**
     * 根据订单号查询门店订单信息
     * @param orderNo
     * @return
     */
    @Override
    public R getErpOrderInfo(String orderNo) {
        R re = R.ok();
        // 订单信息
        ErpOrderEntity erpOrder =  this.getById(orderNo);
        //处理数据用于前台展示
        re.put("erpOrder", erpOrder);

        //订单备注
        List<OrderRemarksEntity> orderRemarksData = orderRemarksService.list(
                new QueryWrapper<OrderRemarksEntity>()
                        .eq("or_del", "0")
                        .eq("or_order_id", orderNo)
        );
        re.put("orderRemarksData", orderRemarksData);

        // 商品列表
        List<ErpOrderItemEntity> orderItemDetailData = erpOrderItemService.list(
                new QueryWrapper<ErpOrderItemEntity>()
                        .eq("order_no",orderNo)
                        .eq("item_del",0)
        );

        //印刷商品需将规格属性进行处理
        for (int i = 0; i <orderItemDetailData.size() ; i++) {
            ErpOrderItemEntity erpOrderItemEntity=orderItemDetailData.get(i);
            String addon = erpOrderItemEntity.getAddon();
            if (addon != null && (erpOrderItemEntity.getAddcartBuyType().equals("fast")||erpOrderItemEntity.getAddcartBuyType().equals("print"))&&addon.startsWith("[{")){
                List<ProductInfoParam> productInfoParamList= addon2ProductInfoParamList(erpOrderItemEntity.getAddon());
                erpOrderItemEntity.setProductInfoParamList(productInfoParamList);
                //拼接成addon;
                StringBuilder addonBuilder=new StringBuilder();
                for (int j=0;j<productInfoParamList.size();j++){
                    ProductInfoParam productInfoParam = productInfoParamList.get(j);
                    addonBuilder.append(productInfoParam.getPartsName()).append(":").append(productInfoParam.getBasicParamStr()).append(";");
                }
                erpOrderItemEntity.setShowAddon(addonBuilder.toString());
            }else{
                erpOrderItemEntity.setShowAddon(addon);
            }
        }

        re.put("orderItemDetailData", orderItemDetailData);

        //查询发票信息,如果为紫云网订单，则还需要查询发票信息
        if(erpOrder.getOrderSource()==OrderSourceEnum.ZIYUN.toInt()){
            //先根据分配信息查询原始单号
            ErpOrderAllotRelevanceEntity erpOrderAllotRelevanceEntity = erpOrderAllotRelevanceService.getOne(new QueryWrapper<ErpOrderAllotRelevanceEntity>()
                    .eq("order_allot_no", orderNo).eq("del", DeleteEnum.NOT_DELETE.toInt()));
            if(erpOrderAllotRelevanceEntity!=null){
                String orderId = erpOrderAllotRelevanceEntity.getOriginalOrderNo();
                OrderTaxEntity orderTax = orderTaxService.getById(orderId);
                //转换成集合便于前台展示
                List<OrderTaxEntity> orderTaxList=new ArrayList<>();
                orderTaxList.add(orderTax);
                re.put("orderTax",orderTaxList);
                re.put("taxTypeEnum",JsonUtils.enumToList(TaxTypeEnum.class));
                re.put("isAllot",1);
            }
        }
        //查询商品分配列表
        // 已分配列表
        Map<String, Object> params = new HashMap<>();
        params.put("orderNo", orderNo);
        params.put("del", DeleteEnum.NOT_DELETE.toInt());
        List<ErpOrderProductionListVo> erpOrderProductionList = erpOrderProductionService.queryProductionList(params);
        re.put("erpOrderProductionList", erpOrderProductionList);
        return re;
    }

    @Override
    public R collectMoneyPage(String[] orderNos) {
        List<ErpOrderEntity> erpOrderList = this.baseMapper.selectBatchIds(Arrays.asList(orderNos));
        // 支付总额
        BigDecimal totalPayableAmount = erpOrderList.stream().map(ErpOrderEntity::getPayableAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
        // 已支付额
        BigDecimal totalPayed = erpOrderList.stream().map(ErpOrderEntity::getPayed).reduce(BigDecimal.ZERO, BigDecimal::add);
        // 应支付额
        BigDecimal payableAmount = totalPayableAmount.subtract(totalPayed);

        return R.ok().put("payableAmount", payableAmount);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R saveErpOrderWithItem(ErpOrderItemDto erpOrderItemDto) {
        ErpOrderEntity erpOrder = erpOrderItemDto.getErpOrder();
        Integer memberId = erpOrder.getMemberId();
        StoreMemberEntity storeMember = new StoreMemberEntity();
        if (erpOrder != null) {
            //查询storeMember表是否存在此客户
            StoreMemberEntity storeMemberEntity = storeMemberService.getOne(new QueryWrapper<StoreMemberEntity>().eq("member_id", memberId)
                                .eq("seller_id",UserUtils.getCurentUser().getSellerId()));
            //如果当前客户不在storeMember
            if (null == storeMemberEntity) {
                //添加数据到storeMember
                //从user_base_info中查询
                UserBaseInfoEntity userBaseInfoEntity = userBaseInfoService.getById(erpOrder.getMemberId());
                storeMember.setMemberId(userBaseInfoEntity.getUserId());
                storeMember.setSellerId(UserUtils.getCurentUser().getSellerId().intValue());
                storeMember.setMerchantsType(MerchantsTypeEnum.VISIT.toCode());
                storeMember.setMerchantsSalesMan(erpOrder.getMerchantsSalesMan());
                storeMember.setAddr(userBaseInfoEntity.getAddress());
                storeMember.setMobile(userBaseInfoEntity.getMobile());
                storeMember.setTel(userBaseInfoEntity.getTel());
                storeMember.setHangsAccountCustomer(0);
                storeMember.setAutoClear(0);
                storeMember.setName(userBaseInfoEntity.getName());
                storeMember.setCreateTime(new Date());
                storeMemberService.save(storeMember);
            } else {
                storeMember = storeMemberEntity;
            }
            List<StoreGoodsProductEntity> storeGoodsProductList = erpOrderItemDto.getStoreGoodsProductList();
            //首先生成订单号
            // 先获取当前登陆用户的sellerId
            Long sellerId = UserUtils.getCurentUser().getSellerId();
            // 订单号生成
            String orderNo = "";
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyMMddHHmm");
            String appendSupplierId = "";
            boolean flag = true;
            do {
                if (sellerId > 0 && sellerId < 10) {
                    appendSupplierId = "0" + sellerId;
                } else if (sellerId >= 10) {
                    appendSupplierId = "" + sellerId;
                } else {
                    throw new RRException("订单号生成失败");
                }
                orderNo = "3" + appendSupplierId + dateFormat.format(new Date()) + (int) (Math.random() * 90 + 10);
                // 判断订单号是否已存在
                ErpOrderEntity checkOrder = this.getById(orderNo);
                if (checkOrder == null || checkOrder.getOrderNo() == null) {
                    flag = false;
                }
            } while (flag);
            erpOrder.setOrderNo(orderNo);
            erpOrder.setOriginalOrderId(Long.valueOf(orderNo));
            erpOrder.setShipStatus(0);
            erpOrder.setReceivedStatus(0);
            erpOrder.setOrderType(1);
            //查询当前用户是否为自营的，为将third_merchant_type设置为1
            SellerInfoEntity sellerInfoEntity = sellerInfoService.getById(UserUtils.getCurentUser().getSellerId());
            if(sellerInfoEntity.getSelf()==1){
                erpOrder.setThirdMerchantType(1);
            }else{
                //如果商户类型为小B
                if(sellerInfoEntity.getSellerType().equals("0")){
                    erpOrder.setThirdMerchantType(2);
                }
                //如果商户类型为工厂
                if(sellerInfoEntity.getSellerType().equals("1")){
                    erpOrder.setThirdMerchantType(3);
                }
            }
            erpOrder.setThirdMerchantId(UserUtils.getCurentUser().getSellerId().intValue());
            //设置为线下门店
            erpOrder.setOrderSource(OrderSourceEnum.OFFlINE.toInt());
            //遍历订单详情集合获取订单总金额
            BigDecimal totalAmount = new BigDecimal(0);
            //总价=价格*数量,商品总值
            for (int i = 0; i < storeGoodsProductList.size(); i++) {
                BigDecimal returnedMoney = storeGoodsProductList.get(i).getTotal();
                totalAmount = totalAmount.add(returnedMoney);
            }
            //订单总额
            erpOrder.setTotalAmount(totalAmount.setScale(2,BigDecimal.ROUND_DOWN));
            //配送费用
            erpOrder.setCostFreight(new BigDecimal(0));

            //true为收取押金
            if (erpOrder.getDeposit()) {
                //部分支付
                erpOrder.setPayStatus(Integer.valueOf(PayStatusEnum.PAY_PART_3.toCode()));
                //实际支付金额
                erpOrder.setPayableAmount(erpOrder.getPayed());
                //收取押金则还需要在user_payment表中生成一条数据

                /* 新增用户支付记录表信息 */
                String paymentsId = UserPaymentUtils.getPaymentsId();
                // 防重复支付单号
                boolean repeat = true;
                do {
                    UserPaymentEntity upe = userPaymentService.getById(paymentsId);
                    if (upe == null) {
                        repeat = false;
                    }
                } while (repeat);
                UserPaymentEntity userPayment = new UserPaymentEntity();
                userPayment.setPaymentId(paymentsId);
                erpOrder.setPaymentId(userPayment.getPaymentId());
                userPayment.setUserId(erpOrder.getMemberId().toString());
                userPayment.setStatus(UserPaymentStatusEnum.SUCC.toCode());
                userPayment.setCurMoney(erpOrder.getPayed());
                userPayment.setOpId(UserUtils.getCurentUser().getUserId().toString());
                //押金
                userPayment.setPayType(PayTypeWayEnum.PAY_DEPOSIT.toCode());
                userPayment.setPayAppId(EnumUtil.getEnumByDesc(PayTypeEnum.class, erpOrder.getPayment()).toCode());
                userPayment.setTPayed(new Date());
                // 获取当前登陆用户ID
                userPayment.setOpId(UserUtils.getCurentUser().getUserId().toString());
                userPaymentService.save(userPayment);

                /* 新增用户支付关联表信息 */
                UserPaymentBillEntity userPaymentBill = new UserPaymentBillEntity();
                userPaymentBill.setRelId(Long.valueOf(erpOrder.getOrderNo()));
                userPaymentBill.setBillType(BillTypeEnum.PAYMENTS.toCode());
                userPaymentBill.setPayObject(PayObjectEnum.ORDER.toCode());
                userPaymentBill.setBillId(userPayment.getPaymentId());
                userPaymentBill.setMoney(userPayment.getMoney());
                userPaymentBillService.save(userPaymentBill);
            } else {
                //未支付
                erpOrder.setPayStatus(PayStatusEnum.NOT_PAY_0.toInt());
            }
            erpOrder.setSource("erp");
            //1为普通订单
            erpOrder.setOrderType(OrderTypeEnum.GENERAL.toInt());
            erpOrder.setDel(false);
            erpOrder.setCreateTime(new Date());
            //新开单
            erpOrder.setProductionStatus(ProductionStatusEnum.NEW_ORDER.toInt());
            this.save(erpOrder);
            //将参数重新封装成erpOrderItem对象
            //创建一个集合用于最终插入到erp_order_item表中
            //定义变量用于统计优惠后的总金额
            BigDecimal payableAmount = new BigDecimal(0);
            //定义一个变量判断是否存在算价错误的问题
            Boolean flg = true;
            List<ErpOrderItemEntity> erpOrderItemList = new ArrayList<ErpOrderItemEntity>();
            for (int i = 0; i < storeGoodsProductList.size(); i++) {
                StoreGoodsProductEntity storeGoodsProduct = storeGoodsProductList.get(i);
                ErpOrderItemEntity erpOrderItem = new ErpOrderItemEntity();
                erpOrderItem.setOrderNo(orderNo);
                erpOrderItem.setWeight(storeGoodsProduct.getWeight());
                erpOrderItem.setProductId(storeGoodsProduct.getProductId());
                erpOrderItem.setName(storeGoodsProduct.getProductName());
                erpOrderItem.setNums(storeGoodsProduct.getQuantity());
                erpOrderItem.setAddon(storeGoodsProduct.getCraft());
                erpOrderItem.setCalculationPriceProcess(storeGoodsProduct.getCalculationPriceProcess());
                erpOrderItem.setAddcartBuyType(storeGoodsProduct.getGoodsType());
                erpOrderItem.setAttributeOption(storeGoodsProduct.getAttributeOption());
                erpOrderItem.setCutModel(storeGoodsProduct.getCutModel());
                erpOrderItem.setQuoteSelfDefineParam(storeGoodsProduct.getQuoteSelfDefineParam());
                erpOrderItem.setItemRemark(storeGoodsProduct.getItemRemark()+";操作人:"+UserUtils.getCurentUser().getUsername());
                erpOrderItem.setGoodsId(storeGoodsProduct.getGoodsId());
                erpOrderItem.setCopy(storeGoodsProduct.getCopy());//份数
                logger.info("商品类型:"+erpOrderItem.getAddcartBuyType()+"--------商品goodsId:"+erpOrderItem.getGoodsId());
                erpOrderItem.setWidth(storeGoodsProduct.getWidth());
                erpOrderItem.setLength(storeGoodsProduct.getLength());
                erpOrderItem.setAmount(storeGoodsProduct.getTotal());
                if(erpOrderItem.getAddcartBuyType().equals(AddcartBuyTypeEnum.PRINT.toCode())||erpOrderItem.getAddcartBuyType().equals(AddcartBuyTypeEnum.FAST.toCode())){
                    BigDecimal price=erpOrderItem.getAmount().divide(erpOrderItem.getNums(),4,BigDecimal.ROUND_HALF_UP).divide(erpOrderItem.getCopy());
                    erpOrderItem.setPrice(price);
                }else{
                    erpOrderItem.setPrice(storeGoodsProduct.getPrice());
                }
                erpOrderItem.setPricingManner(storeGoodsProduct.getPricingManner());
                BigDecimal amount = new BigDecimal(0);
                //如果不是标品，则需要用非标品计算价格
                if (storeGoodsProduct.getGoodsType().equals("print") || storeGoodsProduct.getGoodsType().equals("fast")) {
                    //先根据productId从goods表中获取goods_id
                    GoodsEntity goodsEntity = goodsService.getOne(new QueryWrapper<GoodsEntity>().eq("category_id", erpOrderItem.getProductId()));
                    if(goodsEntity==null){
                        erpOrderItem.setName(storeGoodsProduct.getProductName());
                    }else{
                        erpOrderItem.setName(goodsEntity.getName());
                    }
                    Integer goodsId=erpOrderItem.getGoodsId()==null?999999:erpOrderItem.getGoodsId();
                    erpOrderItem.setGoodsId(goodsId);
                    amount = getNotStandardTotalAmount(erpOrderItem, storeMember);
                }
                //标品计算价格 广告物料
                else if (storeGoodsProduct.getGoodsType().equals("standard") || storeGoodsProduct.getGoodsType().equals("material")||storeGoodsProduct.getGoodsType().equals("design")) {
                   //查询商品是否存在original_productId
                    StoreGoodsProductEntity storeGoodsProductEntity = storeGoodsProductService.getById(erpOrderItem.getProductId());
                    if(storeGoodsProductEntity.getOrigProductId()!=null){
                        GoodsProductEntity goodsProductEntity = goodsProductService.getById(storeGoodsProductEntity.getOrigProductId());
                        if(goodsProductEntity!=null){
                            erpOrderItem.setGoodsId(goodsProductEntity.getGoodsId().intValue());
                        }
                    }
                    //判断门店是否存在对应商品的优惠
                    StoreProductPriceEntity storeProductPrice = storeProductPriceService.getOne(new QueryWrapper<StoreProductPriceEntity>().eq("product_id", erpOrderItem.getProductId())
                            .eq("seller_id", sellerId));
                    if (storeProductPrice == null) {
                        amount = erpOrderItem.getNums().multiply(erpOrderItem.getPrice());
                    } else {
                        amount = getTotalAmount(erpOrderItem, storeMember);
                    }
                }
               // erpOrderItem.setAmount(amount);
                //统计应付金额
                payableAmount = payableAmount.add(amount);
                erpOrderItem.setUnit(storeGoodsProduct.getUnit());
                erpOrderItem.setAddon(storeGoodsProduct.getCraft());
                erpOrderItem.setItemDel(0);
                erpOrderItem.setItemType(OrderItemTypeEnum.PRODUCT.toCode());
                //待分配
                erpOrderItem.setStatus(OrderItemStatusEnum.UN_ALLOTED.toInt());
                erpOrderItemList.add(erpOrderItem);
            }
            //应付金额
            erpOrder.setPayableAmount(payableAmount.setScale(2,BigDecimal.ROUND_DOWN));
            //优惠金额
            BigDecimal pmtGoods = erpOrder.getTotalAmount().subtract(erpOrder.getPayableAmount());
            erpOrder.setPmtGoods(pmtGoods);
            //更新应付金额
            this.saveOrUpdate(erpOrder);
            if (erpOrderItemList.size() > 0) {
                erpOrderItemService.saveBatch(erpOrderItemList);
            }
            //添加新开单日志
            ErpOrderLogEntity erpOrderLogEntity = new ErpOrderLogEntity();
            erpOrderLogEntity.setLogText("新开单");
            erpOrderLogEntity.setOrderNo(erpOrder.getOrderNo());
            erpOrderLogEntity.setCreateTime(new Date());
            erpOrderLogEntity.setCreateName(UserUtils.getCurentUser().getUsername());
            erpOrderLogService.save(erpOrderLogEntity);
            return R.ok();
        } else {
            return R.error("添加订单失败!");
        }
    }

    /**
     * 根据订单号
     * @param orderNo
     * @return
     */
    @Override
    public R getOrderPayInfo(String orderNos) {
        if (StringUtils.isBlank(orderNos)){
            return R.error("订单号为空！");
        }
        List<String>  orderList=Arrays.asList(orderNos.split(","));
        if(orderList.size()==0){
            return R.error("传入订单号为空！");
        }
        //查询订单总额等相关信息
       List<ErpOrderEntity> erpOrderList= this.list(new QueryWrapper<ErpOrderEntity>().in("order_no", orderList));

        Set<Integer> memberIdSet=new HashSet();

        List<RecMoney> recMoneyList =new ArrayList<>();
        for (int i=0;i<erpOrderList.size();i++){
            ErpOrderEntity erpOrder=erpOrderList.get(i);
            //判断订单状态，如果为已完结，则直接提示
            if(erpOrder.getProductionStatus()==ProductionStatusEnum.FINISH.toInt()){
                return  R.error("已完成订单无需进行收银操作!");
            }
            if(erpOrder.getProductionStatus()!=4){
                return  R.error("只有生产完成的订单才能进行收银操作!");
            }
            memberIdSet.add(erpOrder.getMemberId());
            // 应付金额
            BigDecimal payableAmount = erpOrder.getPayableAmount();
            BigDecimal payed = erpOrder.getPayed() == null ? BigDecimal.ZERO : erpOrder.getPayed();
            BigDecimal money = payableAmount.subtract(payed);

            // 将数据重新封装传给前台
            RecMoney recMoney=new RecMoney();
            recMoney.setOrderNo(erpOrder.getOrderNo());
            recMoney.setPayAmount(money);
            recMoneyList.add(recMoney);
        }
        if(memberIdSet.size()!=1){
            return R.error("所选订单不为同一客户!");
        }

        BigDecimal totalMoney= recMoneyList.stream().map(RecMoney::getPayAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
        Map<String,Object> map=new HashMap<>();
        map.put("recMoney",recMoneyList);
        map.put("totalMoney",totalMoney);
        map.put("memberName",erpOrderList.get(0).getMemberName());
        return R.apiOk(map);
    }
    /**
     * 根据订单号查询订单支付，生产单扫码支付
     * @param orderNo
     * @return
     */
    @Override
    public R getErpOrderInfoForPay(String orderNo) {
        R re = R.apiOk();
        // 订单信息
        ErpOrderEntity erpOrder =  this.getById(orderNo);
        //处理数据用于前台展示
        re.put("erpOrder", erpOrder);
        // 商品列表
        List<ErpOrderItemEntity> orderItemDetailData = erpOrderItemService.list(
                new QueryWrapper<ErpOrderItemEntity>()
                        .eq("order_no",orderNo)
                        .eq("item_del",0)
        );

        //印刷商品需将规格属性进行处理
        for (int i = 0; i <orderItemDetailData.size() ; i++) {
            ErpOrderItemEntity erpOrderItemEntity=orderItemDetailData.get(i);
            String addon = erpOrderItemEntity.getAddon();
            if (addon != null && (erpOrderItemEntity.getAddcartBuyType().equals("fast")||erpOrderItemEntity.getAddcartBuyType().equals("print"))){
                List<ProductInfoParam> productInfoParamList= addon2ProductInfoParamList(erpOrderItemEntity.getAddon());
                erpOrderItemEntity.setProductInfoParamList(productInfoParamList);
                //拼接成addon;
                StringBuilder addonBuilder=new StringBuilder();
                for (int j=0;j<productInfoParamList.size();j++){
                    ProductInfoParam productInfoParam = productInfoParamList.get(j);
                    addonBuilder.append(productInfoParam.getPartsName()).append(":").append(productInfoParam.getBasicParamStr()).append(";");
                }
                erpOrderItemEntity.setShowAddon(addonBuilder.toString());
            }else{
                erpOrderItemEntity.setShowAddon(addon);
            }
        }

        re.put("orderItemDetailData", orderItemDetailData);
        return re;
    }


    /**
     * 门店选择订单后，生成批量结算单
     */
    @Override
    public R generateBatchProduct(List<String> orderList){
        if(orderList.size()==0){
            return R.error("传入订单号为空！");
        }
        if(orderList.size()==1){
            return R.error("单个订单无需生成批量结算单!");
        }

        //查询订单总额等相关信息
        List<ErpOrderEntity> erpOrderList= this.list(new QueryWrapper<ErpOrderEntity>().in("order_no", orderList));

        Set<Integer> memberIdSet=new HashSet();

        //将订单号拼接成一个字符串用于生成二维码
        StringBuilder orderSb=new StringBuilder();

        List<RecMoney> recMoneyList =new ArrayList<>();
        for (int i=0;i<erpOrderList.size();i++){
            ErpOrderEntity erpOrder=erpOrderList.get(i);
            //判断订单状态，如果为已完结，则直接提示
            if(erpOrder.getProductionStatus()==ProductionStatusEnum.FINISH.toInt()){
                return  R.error("已完成订单无需进行收银操作!");
            }
            if(erpOrder.getProductionStatus()!=4){
                return  R.error("只有生产完成的订单才能进行收银操作!");
            }
            if(i<erpOrderList.size()-1){
                orderSb.append(erpOrder.getOrderNo()).append(",");
            }else{
                orderSb.append(erpOrder.getOrderNo());
            }
            memberIdSet.add(erpOrder.getMemberId());
            // 应付金额
            BigDecimal payableAmount = erpOrder.getPayableAmount();
            BigDecimal payed = erpOrder.getPayed() == null ? BigDecimal.ZERO : erpOrder.getPayed();
            BigDecimal money = payableAmount.subtract(payed);

            // 将数据重新封装传给前台
            RecMoney recMoney=new RecMoney();
            recMoney.setOrderNo(erpOrder.getOrderNo());
            recMoney.setPayAmount(money);
            recMoneyList.add(recMoney);
        }
        if(memberIdSet.size()!=1){
            return R.error("所选订单不为同一客户!");
        }
        //获取第一个订单用于展示客户的基本信息
        ErpOrderEntity erpOrderEntity=erpOrderList.get(0);
        BigDecimal totalMoney= recMoneyList.stream().map(RecMoney::getPayAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
        Map<String,Object> data=new HashMap<>();
        data.put("recMoney",recMoneyList);
        data.put("totalMoney",totalMoney);
        data.put("erpOrder",erpOrderEntity);
        data.put("orderNos",orderSb.toString());
        SysUserEntity curentUser = UserUtils.getCurentUser();
        SellerInfoEntity sellerInfoEntity = sellerInfoService.getById(curentUser.getSellerId());
        return R.ok().put("data",data).put("curentUser",curentUser).put("sellerInfoEntity",sellerInfoEntity);
    }


    /**
     * 自营门店通过结算单进行扫码支付开始
     * @param
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R beginOrderPay(Map<String,Object> map) {
       String orderNo= map.get("orderNo").toString();
       if(StringUtils.isBlank(orderNo)){
           return  R.error("订单号不存在!");
       }
        List<String>  orderNoList= Arrays.asList(orderNo.split(","));
        //查询订单信息
        List<ErpOrderEntity> erpOrderList=this.list(new QueryWrapper<ErpOrderEntity>().in("order_no",orderNoList));
        for (int i=0;i<erpOrderList.size();i++){
            ErpOrderEntity erpOrder=erpOrderList.get(i);
            //判断订单状态，如果为已完结，则直接提示
            if(erpOrder.getProductionStatus()==ProductionStatusEnum.FINISH.toInt()){
                return  R.error("已完成订单无需进行扫码支付操作!");
            }
            if(erpOrder.getProductionStatus()!=4){
                return  R.error("只有生产完成的订单才能进行扫码支付操作!");
            }
            if(erpOrder.getPayed()==null){
                erpOrder.setPayed(BigDecimal.ZERO);
            }
        }

       String ip=map.get("ip").toString();
       String openid=map.get("openid").toString();
        // 应付金额
        BigDecimal payableAmount = erpOrderList.stream().map(ErpOrderEntity::getPayableAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal payed = erpOrderList.stream().map(ErpOrderEntity::getPayed).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal money = payableAmount.subtract(payed);

        //添加支付单信息
        UserPaymentEntity userPayment = new UserPaymentEntity();
        // 收款单号
        String paymentId = null;
        // 判断收款单号是否重复
        boolean repeat = true;
        do {
            paymentId = UserPaymentUtils.getPaymentsId();
            List<UserPaymentEntity> countList = userPaymentService.list(new QueryWrapper<UserPaymentEntity>().eq("payment_id", paymentId));
            if (countList == null || countList.size() <= 0) {
                repeat = false;
            }
        } while (repeat);
        userPayment.setPaymentId(paymentId);
        userPayment.setMoney(money);
        userPayment.setCurMoney(money);
        userPayment.setUserId(erpOrderList.get(0).getMemberId().toString());
        userPayment.setStatus("ready");
        userPayment.setPayName("微信");
        userPayment.setTPayed(new Date());
        userPayment.setPayType("online");//线下支付
        userPayment.setTBegin(new Date());
        userPayment.setPayAppId(EnumUtil.getEnumByDesc(PayTypeEnum.class, "微信").toCode());
        //用户支付记录表;
        userPaymentService.save(userPayment);

        List<UserPaymentBillEntity> userPaymentBillList=new ArrayList<>();
        for (int i=0;i<erpOrderList.size();i++){
            ErpOrderEntity erpOrder=erpOrderList.get(i);
            // 订单，支付单关联信息
            UserPaymentBillEntity userPaymentBill = new UserPaymentBillEntity();
            userPaymentBill.setRelId(Long.valueOf(erpOrder.getOrderNo()));
            userPaymentBill.setBillId(userPayment.getPaymentId());
            userPaymentBill.setPayObject(PayObjectEnum.ORDER.toCode());
            userPaymentBill.setBillType(BillTypeEnum.PAYMENTS.toCode());
            userPaymentBill.setMoney( erpOrder.getPayableAmount().subtract(erpOrder.getPayed()));
            userPaymentBillList.add(userPaymentBill);
        }
        userPaymentBillService.saveBatch(userPaymentBillList);
        List<BatchOrderPaymentEntity> batchOrderPaymentList=new ArrayList<BatchOrderPaymentEntity>();
        //添加信息到批量扫码支付流水表中
        for (int i=0;i<orderNoList.size();i++){
            BatchOrderPaymentEntity batchOrderPaymentEntity=new BatchOrderPaymentEntity();
            batchOrderPaymentEntity.setOrderNo(orderNoList.get(i));
            batchOrderPaymentEntity.setPaymentId(paymentId);
            batchOrderPaymentEntity.setDel(false);
            batchOrderPaymentList.add(batchOrderPaymentEntity);
        }
        batchOrderPaymentService.saveBatch(batchOrderPaymentList);
        //调用微信支付
        SortedMap<Object,Object> weixinPayMap = new TreeMap<Object,Object>();
        String notifyUrl="http://test.pop2.11ziyun.com/port/order/orderPayWeixinCallBack";
        weixinPayMap.put("out_trade_no", paymentId);
        weixinPayMap.put("total_fee", money.multiply(new BigDecimal(100)).intValue());
        weixinPayMap.put("notify_url", notifyUrl);
        weixinPayMap.put("trade_type", "JSAPI");
        weixinPayMap.put("spbill_create_ip",ip);
        weixinPayMap.put("openid",openid);
        weixinPayMap.put("detail","中浩紫云");
        weixinPayMap.put("attach", "中浩紫云");
        PayResult<Map<String, Object>> weixinpay = weixinpayService.weixinpay(weixinPayMap, "wap");
        return R.apiOk().put("data", weixinpay.getData());
    }

    /**
     *   门店结算单扫码支付回调
     * @param
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean orderPayWeixinCallBack(HttpServletRequest request) {
            try {
                BufferedReader reader = request.getReader();
                String line = "";
                StringBuffer inputString = new StringBuffer();
                while ((line = reader.readLine()) != null) {
                    inputString.append(line);
                }
                if (reader != null) {
                    reader.close();
                }
                if (StringUtils.isEmpty(inputString.toString())) {
                    logger.error("微信支付回调失败，未获取到微信返回的结果,接收报文：" + inputString.toString());
                }

                SortedMap<Object, Object> mapRdata = JdomParseXmlUtils.getWXPayResult(inputString.toString());
                String return_code = mapRdata.get("return_code").toString(); // 返回状态
                String sign = mapRdata.get("sign").toString(); // 返回状态
                if (!"SUCCESS".equalsIgnoreCase(return_code)) {
                    logger.error("微信支付回调失败,接收报文：" + inputString.toString());
                }
                mapRdata.remove("sign");
                // 反校验签名
                String fsign = WXSignUtils.createSign("UTF-8", mapRdata, wxPayConfig.getKey());

                String pcsign = WXSignUtils.createSign("UTF-8", mapRdata, wxPayConfig.getPcKey());

                if (!fsign.equals(sign) && !pcsign.equals(sign)) {
                    logger.error("微信支付回调失败,反校验签名失败,接收报文：" + inputString.toString());
                    return false;
                }
                String paymentId = mapRdata.get("out_trade_no").toString(); // 商城支付单号
                String trade_no = mapRdata.get("transaction_id").toString(); // 微信单号
                BigDecimal money = new BigDecimal(mapRdata.get("total_fee").toString()).divide(BigDecimal.valueOf(100));
                return checkAndUpPayStatus(paymentId, trade_no, money);
            }catch (IOException e){
                return false;
            }
    }

    /**
     * 门店结算单扫码支付校验参数以及返回给微信状态
     * @param paymentId
     * @param tradeNo
     * @param money
     * @return
     */
    private boolean checkAndUpPayStatus(String paymentId, String tradeNo, BigDecimal money ){
        UserPaymentEntity userPayment = userPaymentService.getById(paymentId);
        if("succ".equals(userPayment.getStatus())){
            return true;
        }
        // 状态比对
        if (!"ready".equals(userPayment.getStatus())) {
            logger.error("订单支付流水状态不为ready;支付单号:"+paymentId);
            return false;
        }
        // 比对金额
        BigDecimal scMoney = userPayment.getMoney();// 商城金额
        if (scMoney.compareTo(money) != 0) {
            // 支付金额不一致
            logger.error("支付金额不一致" +":支付单号:"+paymentId+"，金额为:"+scMoney+"元;微信返回金额为:"+money+"元");
            return false;
        }
        userPayment.setTradeNo(tradeNo);
        // 业务处理
        this.updatePayAndOrderStatus(userPayment);
        return true;
    }

    /**
     * 修改支付流水状态以及订单状态，业务代码
     * @param userPaymentEntity
     */
    @Transactional(rollbackFor = Exception.class)
    public void updatePayAndOrderStatus(UserPaymentEntity userPaymentEntity) {
        String paymentId = userPaymentEntity.getPaymentId();
        BigDecimal money =userPaymentEntity.getMoney();
        Date date=new Date();
        userPaymentEntity.setTPayed(date);
        userPaymentEntity.setStatus("succ");//修改为支付成功
        userPaymentService.updateById(userPaymentEntity);
        //先根据支付单号去扫码批量支付流水表中找到所有订单
       List<BatchOrderPaymentEntity> batchList= batchOrderPaymentService.list(new QueryWrapper<BatchOrderPaymentEntity>()
                .eq("payment_id",paymentId).eq("status","ready").eq("del",DeleteEnum.NOT_DELETE));
        List<String> orderNoList=new ArrayList<>();//定义集合存放订单号
        for (int i=0;i<batchList.size();i++){
            BatchOrderPaymentEntity  batchOrderPayment=batchList.get(i);
            orderNoList.add(batchOrderPayment.getOrderNo());
            batchOrderPayment.setPaymentTime(new Date());
            batchOrderPayment.setStatus("succ");
        }
        //修改支付信息
        batchOrderPaymentService.updateBatchById(batchList);
        List<ErpOrderEntity> orderList=this.list(new QueryWrapper<ErpOrderEntity>().in("order_no",orderNoList));
        //日志集合
        List<ErpOrderLogEntity> erpOrderLoglist=new ArrayList<>();
        for (int i=0;i<orderList.size();i++){
            //收款成功后，更改订单状态为已完结,已支付
            ErpOrderEntity erpOrder = orderList.get(i);
            //判断是否为自提，如果为自提，则收银结算将发货状态和收货状态更改为已收货
            if (erpOrder.getSendType() == SendTypeEnum.PICK_UP.toInt()) {
                //1为已发货
                erpOrder.setShipStatus(1);
                erpOrder.setReceivedStatus(ReceivedStatusEnum.RECEIVED.toInt());
                erpOrder.setReceivedTime(new Date());
            }
            // 修改已支付金额
            BigDecimal payed = erpOrder.getPayed().add(money);
            erpOrder.setPayableAmount(payed);
            erpOrder.setPayed(payed);
            erpOrder.setPayment("微信");
            erpOrder.setPayStatus(Integer.valueOf(PayStatusEnum.ALREADY_PAY_1.toCode()));
            erpOrder.setProductionStatus(ProductionStatusEnum.FINISH.toInt());
            erpOrder.setPaymentTime(date);
            erpOrder.setPaymentId(paymentId);
            erpOrder.setLastModifiedTime(date);
            erpOrder.setIsUrgent(0);

            //创建erp_order_log
            ErpOrderLogEntity erpOrderLog = new ErpOrderLogEntity();
            erpOrderLog.setOrderNo(erpOrder.getOrderNo());
            erpOrderLog.setCreateName("微信扫码");
            erpOrderLog.setCreateTime(new Date());
            erpOrderLog.setCreateBy(erpOrder.getThirdMerchantId().toString());
            erpOrderLog.setLogText("门店结算单扫码收款");
            erpOrderLoglist.add(erpOrderLog);
        }
        if(orderList.size()>0){
            this.updateBatchById(orderList);
        }


        // 同步更新 order_info 支付信息，门店订单直接更新订单完结状态，商城订单交由计划任务处理
        List<OrderInfoEntity> orderInfoList=orderInfoService.list(new QueryWrapper<OrderInfoEntity>().in("order_id",orderNoList));
        for (int i=0;i<orderInfoList.size();i++){
            OrderInfoEntity orderInfo = orderInfoList.get(i);
            if (orderInfo != null) {
                Map<String, Object> updateMap = new HashMap<>();
                for (int j=0;j<orderList.size();j++){
                    ErpOrderEntity erpOrder = orderList.get(i);
                    if(erpOrder.getOrderNo().equals(orderInfo.getOrderId())){
                        String source = orderInfo.getSource();
                        if (StringUtils.equals(source, "erp")) {
                            orderInfo.setStatus(OrderInfoStatusEnum.FINISH.toCode());
                        }
                        orderInfo.setDiscount( erpOrder.getDiscount());
                        orderInfo.setPayableAmount(erpOrder.getPayableAmount());
                        orderInfo.setPayed(erpOrder.getPayed());
                        orderInfo.setPayStatus(erpOrder.getPayStatus().toString());
                    }
                }
            }
        }
        //修改orderInfo信息
        if(orderInfoList.size()>0){
            orderInfoService.updateBatchById(orderInfoList);
        }
        if(erpOrderLoglist.size()>0){
            erpOrderLogService.saveBatch(erpOrderLoglist);
        }
    }
    @Override
    public R getBatchReceviceMoneyData(List<String> orderNoList){
        if(orderNoList.size()==0){
            return R.error("请至少选中一行再进行操作");
        }
        //查询订单总额等相关信息
        List<ErpOrderEntity> erpOrderList= this.list(new QueryWrapper<ErpOrderEntity>().in("order_no", orderNoList));
        Set<Integer> memberIdSet=new HashSet();
        //将订单号拼接成一个字符串用于生成二维码
        StringBuilder orderSb=new StringBuilder();
        //订单应付总金额
        BigDecimal total=new BigDecimal(0);
        //订单应付总金额
        BigDecimal totalAmount=new BigDecimal(0);
        //订单已付总金额
        BigDecimal payedAmount=new BigDecimal(0);
        for (int i=0;i<erpOrderList.size();i++){
            ErpOrderEntity erpOrder=erpOrderList.get(i);
            //判断订单状态，如果为已完结，则直接提示
            if(erpOrder.getProductionStatus()==ProductionStatusEnum.FINISH.toInt()){
                return  R.error("订单"+erpOrder.getOrderNo()+"为已完成订单无需进行收银操作!");
            }
            if(erpOrder.getProductionStatus()!=4){
                return  R.error("订单"+erpOrder.getOrderNo()+"不为生产完成!只有生产完成的订单才能进行收银操作!");
            }
            memberIdSet.add(erpOrder.getMemberId());
            if(i<erpOrderList.size()-1){
                orderSb.append(erpOrder.getOrderNo()).append(",");
            }else{
                orderSb.append(erpOrder.getOrderNo());
            }
            // 应付金额
            BigDecimal payableAmount = erpOrder.getPayableAmount();
            BigDecimal payed = erpOrder.getPayed() == null ? BigDecimal.ZERO : erpOrder.getPayed();
            BigDecimal money = payableAmount.subtract(payed);
            total=total.add(erpOrder.getTotalAmount());
            totalAmount=totalAmount.add(money);
            payedAmount=payedAmount.add(payed);
        }
        if(memberIdSet.size()!=1){
            return R.error("所选订单不为同一客户!");
        }
        //获取第一个订单用于展示客户的基本信息
        ErpOrderEntity erpOrderEntity=erpOrderList.get(0);

        //根据会员查询会员折扣
        Integer memberId = erpOrderList.get(0).getMemberId();
        //当前用户sellerID
         Long sellerId=UserUtils.getCurentUser().getSellerId();
       //根据会员名查询折扣率
        Map<String,Object> map=new HashMap<>();
        map.put("memberId",memberId);
        map.put("sellerId",sellerId);
        BigDecimal discountRate=storeFavouredPriceService.getDiscountRateByMemberId(map);
        //定义一个变量存储用户余额
        BigDecimal advance=new BigDecimal(0);
        //查询用户余额度
        UserWalletEntity userWallet= userWalletService.getById(memberId);
        if(userWallet!=null){
            advance=userWallet.getAdvance();
        }
        Map<String,Object> batchRecMoney=new HashMap<>();
        batchRecMoney.put("payName","扫码支付");//默认扫码支付
        batchRecMoney.put("memberName",erpOrderEntity.getMemberName());//会员名称
        batchRecMoney.put("total",total);//订单总额
        batchRecMoney.put("money",totalAmount);//收款金额
        batchRecMoney.put("payedAmount",payedAmount);//已付总额
        batchRecMoney.put("advance",advance);
        batchRecMoney.put("memberId",memberId);
        batchRecMoney.put("orderNos",orderSb.toString());
        return R.ok().put("payTypeEnum",JsonUtils.enumToList(PayTypeEnum.class))
                .put("batchRecMoney",batchRecMoney);
    }


    @Override
    public ErpOrderEntity selectByOrderId(Long orderId) {
        Map<String, Object> param = new HashMap<>(1);
        param.put("original_order_id", orderId);
        param.put("del", 0);
        List<ErpOrderEntity> erpOrderEntities = this.baseMapper.selectByMap(param);
        if (erpOrderEntities.size() == 0) {
            return null;
        }
        return erpOrderEntities.get(0);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R monthlyOrderPay(MonthlyOrderPayDto monthlyOrderPayDto) {
        String[] orderNoArr = monthlyOrderPayDto.getOrderNo();
        List<ErpOrderEntity> erpOrderList = this.baseMapper.selectBatchIds(Arrays.asList(orderNoArr));
        BigDecimal totalPayableAmount = erpOrderList.stream().map(ErpOrderEntity::getPayableAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal totalPayed = erpOrderList.stream().map(ErpOrderEntity::getPayed).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal payableAmount = totalPayableAmount.subtract(totalPayed);
        BigDecimal payed = monthlyOrderPayDto.getPayed();
        BigDecimal discount = payed.subtract(payableAmount);
        int compare = discount.compareTo(BigDecimal.ZERO);
        String orderNoMax = null;
        if (compare != 0) {
            // 客户填写调价金额不为0，从待付款订单号中找出应付金额最大值，
            // 并记录调价优惠信息，其他应收金额照常收取
            Optional<ErpOrderEntity> max = erpOrderList.stream().max((x, y) -> x.getPayableAmount().compareTo(y.getPayableAmount()));
            ErpOrderEntity erpOrderMax = max.get();
            orderNoMax = erpOrderMax.getOrderNo();
        }
        Map<String, Object> updateMap = new HashMap<>();
        String payment = monthlyOrderPayDto.getPayment();
        String paymentTime = DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss");
        for (ErpOrderEntity erpOrder : erpOrderList) {
            /* 更新用户支付记录 */
            String orderNo = erpOrder.getOrderNo();
            BigDecimal pAmount = erpOrder.getPayableAmount();
            String paymentsId = UserPaymentUtils.getPaymentsId();
            boolean repeat = true;
            do {
                UserPaymentEntity upe = userPaymentService.getById(paymentsId);
                if (upe == null) {
                    repeat = false;
                }
            } while (repeat);
            UserPaymentEntity userPayment = new UserPaymentEntity();
            userPayment.setPaymentId(paymentsId);
            userPayment.setMoney(pAmount);
            userPayment.setCurMoney(pAmount);
            userPayment.setUserId(erpOrder.getMemberId().toString());
            userPayment.setStatus("succ");
            userPayment.setTPayed(new Date());
            userPayment.setSource("erp");
            userPayment.setPayAppId(payment);
            for (PayTypeEnum e : PayTypeEnum.values()) {
                if (payment.equals(e.toCode()) && !("refundment".equals(payment))) {
                    userPayment.setPayName(e.toDescribe());
                    if (payment.startsWith("offline")) {
                        userPayment.setPayType("offline");
                    } else {
                        userPayment.setPayType("online");
                    }
                    break;
                } else {
                    userPayment.setPayType("offline");
                }
            }
            userPayment.setOpId(UserUtils.getCurentUser().getUserId().toString());
            userPaymentService.save(userPayment);

            UserPaymentBillEntity userPaymentBill = new UserPaymentBillEntity();
            userPaymentBill.setRelId(Long.valueOf(orderNo));
            if ("refundment".equals(payment)) {
                userPaymentBill.setBillType("refunds");
            } else {
                userPaymentBill.setBillType("payments");
            }
            userPaymentBill.setPayObject("order");
            userPaymentBill.setBillId(userPayment.getPaymentId());
            userPaymentBill.setMoney(userPayment.getMoney());
            userPaymentBillService.save(userPaymentBill);

            /* 更新订单状态信息 */
            if (orderNoMax != null && StringUtils.equals(orderNoMax, orderNo)) {
                pAmount = pAmount.add(discount);
                updateMap.put("discount", discount);
            }

            updateMap.put("paymentId", paymentsId);
            updateMap.put("payment", payment);
            updateMap.put("payableAmount", pAmount);
            updateMap.put("payed", pAmount);
            updateMap.put("payStatus", PayStatusEnum.ALREADY_PAY_1.toCode());
            updateMap.put("paymentTime", paymentTime);
            updateMap.put("productionStatus", ProductionStatusEnum.FINISH.toInt());
            if(erpOrder.getSendType() == 1){
                String formatTime = DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss");
                if(erpOrder.getReceivedTime() == null){
                    updateMap.put("receivedStatus", ReceivedStatusEnum.RECEIVED.toInt());
                    updateMap.put("receivedTime", formatTime);
                    updateMap.put("sendTime", formatTime);
                    updateMap.put("shipStatus", ShipStatusEnum.shipped.toCode());
                }
            }
            this.baseMapper.updateByMap(updateMap, orderNo);

            // 判断order_info表是否有数据（ 2018-11-02 旧版遗留数据） ,需要同步更新状态
            OrderInfoEntity orderInfo = orderInfoService.getById(orderNo);
            if (orderInfo != null) {
                updateMap.remove("paymentId");
                updateMap.remove("payment");
                updateMap.remove("paymentTime");
                updateMap.remove("productionStatus");
                updateMap.put("status", OrderInfoStatusEnum.FINISH.toCode());
                orderInfoService.updateByMap(updateMap, orderNo);
            }

            ErpOrderLogEntity erpOrderLog = new ErpOrderLogEntity();
            erpOrderLog.setOrderNo(orderNo);
            erpOrderLog.setCreateName(UserUtils.getCurentUser().getUsername());
            erpOrderLog.setCreateTime(new Date());
            erpOrderLog.setCreateBy(UserUtils.getCurentUser().getSellerId().toString());
            erpOrderLog.setLogText("门店月结订单收款");
            erpOrderLogService.save(erpOrderLog);
        }

        return R.ok();
    }


    //取消订单(门店)
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R cancelOrder(ErpOrderLogEntity erpOrderLogs) {
            //先根据订单号判断订单的生产状态
            ErpOrderEntity erpOrderEntity = this.baseMapper.selectOne(new QueryWrapper<ErpOrderEntity>().eq("order_no", erpOrderLogs.getOrderNo()));

            if (erpOrderEntity.getProductionStatus() != 7) {
                return R.error("只有新开单才能取消");
            } else {
                //将订单状态变为已作废
                erpOrderEntity.setProductionStatus(ProductionStatusEnum.CANCELLED.toInt());
                this.baseMapper.updateById(erpOrderEntity);
                //先查询当前订单下的所有订单商品
                List<ErpOrderItemEntity> erpOrderItemEntityList = erpOrderItemService.selectListByErpOrder(erpOrderLogs.getOrderNo());
                for (int i = 0; i < erpOrderItemEntityList.size(); i++) {
                    erpOrderItemEntityList.get(i).setItemDel(1);
                }
                //删除商品详情表
                if (erpOrderItemEntityList.size() > 0) {
                    erpOrderItemService.updateBatchById(erpOrderItemEntityList);
                }
                //判断orderInfo表中是否存在数据存在也要同步修改
                OrderInfoEntity orderInfoEntity = orderInfoService.getById(erpOrderEntity.getOrderNo());
                if(orderInfoEntity!=null){
                    orderInfoEntity.setStatus(OrderInfoStatusEnum.CANCEL.toCode());
                    orderInfoService.updateById(orderInfoEntity);
                }

                List<OrderItemEntity> orderItemEntityList=orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_id",erpOrderEntity.getOrderNo()));
                if(orderItemEntityList.size()>0){
                    orderItemEntityList.stream().forEach(
                            orderItemEntity -> orderItemEntity.setDeleteFlag(true)
                    );
                   orderItemService.updateBatchById(orderItemEntityList);
                }

                erpOrderLogService.save(erpOrderLogs);
            }
        return R.ok();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R saveErpOrderLogistics(ErpLogisticsDto erpLogisticsDto) {
        ErpLogisticsEntity erpLogisticsEntity = erpLogisticsDto.getErpLogisticsEntity();
        List<ErpLogisticsItemEntity> erpLogisticsItemList = erpLogisticsDto.getErpLogisticsItemList();
        if (erpLogisticsEntity != null) {
            erpLogisticsEntity.setSellerId(UserUtils.getCurentUser().getSellerId());
            erpLogisticsEntity.setCreateName(UserUtils.getCurentUser().getUsername());
            erpLogisticsEntity.setProductionId("0");
            erpLogisticsEntity.setOrderId(Long.valueOf(erpLogisticsEntity.getOrderNo()));
            erpLogisticsService.save(erpLogisticsEntity);
        }
        for (int i = 0; i < erpLogisticsItemList.size(); i++) {
            erpLogisticsItemList.get(i).setLogiId(erpLogisticsEntity.getLogiId());
        }
        if (erpLogisticsItemList.size() > 0) {
            erpLogisticsItemService.saveBatch(erpLogisticsItemList);
        }

        // 判断是否订单出库（紫云网订单、挂账订单添加物流），修改订单发货信息
        int sendType = erpLogisticsEntity.getSendType();
        if (sendType == LogisticsSendTypeEnum.ORDER.toInt()){
            String orderNo = erpLogisticsEntity.getOrderNo();
            ErpOrderEntity erpOrder = this.getById(orderNo);
            Integer shipStatus = erpOrder.getShipStatus();
            Integer orderSource = erpOrder.getOrderSource();
            Boolean onCredit = erpOrder.getOnCredit();
            if (shipStatus.intValue() == ShipStatusEnum.NOT_SHIPPED.toInt() &&  (orderSource.intValue() == 1 || onCredit)){
                int logiType = erpLogisticsEntity.getLogiType();
                Map<String, Object> updateMap = new HashMap<>();
                Map<String,Object> orderInfoMap=new HashMap<>();
                Date currDate = new Date();
                updateMap.put("shipStatus", ShipStatusEnum.shipped.toCode());
                updateMap.put("sendTime",DateUtils.format(currDate, "yyyy-MM-dd HH:mm:ss"));
                if (logiType == 3){// 自提
                    updateMap.put("deliveryTime", DateUtils.format(currDate, "yyyy-MM-dd HH:mm:ss"));
                }else {// 非自提，默认7天确认收货sss
                    updateMap.put("deliveryTime", DateUtils.format(DateUtils.addDateDays(currDate, 7), "yyyy-MM-dd HH:mm:ss"));
                }
                this.updateByMap(updateMap, orderNo);
                orderInfoMap.put("shipStatus","1");
                orderInfoService.updateByMap(orderInfoMap, orderNo);
            }
        }
        ErpOrderLogEntity erpOrderLog = new ErpOrderLogEntity();
        erpOrderLog.setOrderNo(erpLogisticsEntity.getOrderNo());
        erpOrderLog.setCreateName(UserUtils.getCurentUser().getUsername());
        erpOrderLog.setCreateTime(new Date());
        erpOrderLog.setCreateBy(UserUtils.getCurentUser().getSellerId().toString());
        erpOrderLog.setLogText("订单出库操作");
        erpOrderLogService.save(erpOrderLog);
        return R.ok();
    }


    /**
     * 收银结算
     *
     * @param params
     * @return
     */

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R saveReceviceMoneyData(Map<String, Object> params) {
        //先根据支付方式查询是否为预存款支付，为预存款则需校验余额是否够
        String payName = params.get("payName").toString();
        String memberId = params.get("memberId").toString();
        BigDecimal money = new BigDecimal(params.get("money").toString());
        String orderNo = params.get("orderNo").toString();
        if (!StringUtils.isNotBlank(payName)) {
            return R.error("获取订单相关数据错误，收银失败!");
        }
        if (!StringUtils.isNotBlank(orderNo)) {
            return R.error("获取订单相关数据错误，收银失败!");
        }
        if (!StringUtils.isNotBlank(payName)) {
            return R.error("获取订单相关数据错误，收银失败!");
        }
        //收款成功后，更改订单状态为已完结,已支付
        ErpOrderEntity erpOrder = this.getById(orderNo);
        //先判断订单状态是否为已完结
        if(erpOrder.getProductionStatus()==ProductionStatusEnum.FINISH.toInt()){
            return  R.error("当前订单已完结，请刷新页面查看订单最新状态!");
        }
        BigDecimal advance=new BigDecimal(0);
        //根据会员id去数据库查询余额
        UserWalletEntity userWalletEntity = userWalletService.getById(memberId);
        if(userWalletEntity!=null){
            advance = userWalletEntity.getAdvance();
        }
        //如果是预存款支付
        if (payName.equals(PayTypeEnum.DEPOSIT.toDescribe())) {
            if (money.compareTo(advance) > 0) {
                return R.error("客户账户余额不足支付，请充值！");
            }
        }
        //添加支付单信息
        UserPaymentEntity userPayment = new UserPaymentEntity();
        // 收款单号
        String paymentId = UserPaymentUtils.getPaymentsId();
        // 判断收款单号是否重复
        boolean repeat = true;
        do {
            List<UserPaymentEntity> countList = userPaymentService.list(new QueryWrapper<UserPaymentEntity>().eq("payment_id", paymentId));
            if (countList == null || countList.size() <= 0) {
                repeat = false;
            }
        } while (repeat);
        userPayment.setPaymentId(paymentId);
        userPayment.setMoney(money);
        userPayment.setCurMoney(money);
        userPayment.setUserId(memberId);
        userPayment.setStatus("succ");
        userPayment.setPayName(payName);
        userPayment.setTPayed(new Date());
        userPayment.setPayType("offline");//线下支付
        userPayment.setPayAppId(EnumUtil.getEnumByDesc(PayTypeEnum.class, payName).toCode());
        //用户支付记录表;
        userPaymentService.save(userPayment);
        // 订单，支付单关联信息
        UserPaymentBillEntity userPaymentBill = new UserPaymentBillEntity();
        userPaymentBill.setRelId(Long.valueOf(orderNo));
        userPaymentBill.setBillId(userPayment.getPaymentId());
        userPaymentBill.setPayObject(PayObjectEnum.ORDER.toCode());
        userPaymentBill.setBillType(BillTypeEnum.PAYMENTS.toCode());
        userPaymentBill.setMoney(userPayment.getMoney());
        userPaymentBillService.save(userPaymentBill);
        //创建erp_order_log
        ErpOrderLogEntity erpOrderLog = new ErpOrderLogEntity();
        erpOrderLog.setOrderNo(orderNo);
        erpOrderLog.setCreateName(UserUtils.getCurentUser().getUsername());
        erpOrderLog.setCreateTime(new Date());
        erpOrderLog.setCreateBy(UserUtils.getCurentUser().getSellerId().toString());
        erpOrderLog.setLogText("门店收款");
        erpOrderLogService.save(erpOrderLog);


        //判断是否为自提，如果为自提，则收银结算将发货状态和收货状态更改为已收货
        if (erpOrder.getSendType() == SendTypeEnum.PICK_UP.toInt()) {
            //1为已发货
            erpOrder.setShipStatus(1);
            erpOrder.setReceivedStatus(ReceivedStatusEnum.RECEIVED.toInt());
            erpOrder.setReceivedTime(new Date());
        }
        // 修改已支付金额
        BigDecimal payed = erpOrder.getPayed().add(money);
        // 抹零金额添加至调价
        BigDecimal discount = erpOrder.getDiscount();
        BigDecimal payableAmount = erpOrder.getPayableAmount();
        BigDecimal subtract = payed.subtract(payableAmount);
        discount = subtract.add(discount);
        erpOrder.setDiscount(discount);
        erpOrder.setPayableAmount(payed);
        erpOrder.setPayed(payed);
        erpOrder.setPayment(payName);
        erpOrder.setPayStatus(Integer.valueOf(PayStatusEnum.ALREADY_PAY_1.toCode()));
        erpOrder.setProductionStatus(ProductionStatusEnum.FINISH.toInt());
        erpOrder.setPaymentTime(new Date());
        erpOrder.setPaymentId(userPayment.getPaymentId());
        erpOrder.setLastModifiedTime(new Date());
        erpOrder.setIsUrgent(0);
        this.updateById(erpOrder);

        // 同步更新 order_info 支付信息，门店订单直接更新订单完结状态，商城订单交由计划任务处理
        OrderInfoEntity orderInfo = orderInfoService.getById(orderNo);
        if (orderInfo != null) {
            Map<String, Object> updateMap = new HashMap<>();
            String source = orderInfo.getSource();
            if (StringUtils.equals(source, "erp")) {
                updateMap.put("status", OrderInfoStatusEnum.FINISH.toCode());
            }
            updateMap.put("discount", erpOrder.getDiscount());
            updateMap.put("payableAmount", erpOrder.getPayableAmount());
            updateMap.put("payed", erpOrder.getPayed());
            updateMap.put("payStatus", erpOrder.getPayStatus().toString());
            orderInfoService.updateByMap(updateMap, orderNo);
        }

        //如果是预存款支付则还需要操作
        //user_advance添加一条扣款记录
        //  判断false 没有扣款
        if (payName.equals(PayTypeEnum.DEPOSIT.toDescribe())) {
            UserAdvanceEntity userAdvance = new UserAdvanceEntity();
            userAdvance.setUserId(Integer.valueOf(memberId));
            userAdvance.setPaymentId(userPayment.getPaymentId());
            userAdvance.setMoney(money);
            userAdvance.setMessage("门店收款支付订单");
            userAdvance.setMtime(new Date());
            userAdvance.setOrderId(Long.valueOf(orderNo));
            userAdvance.setPaymethod(EnumUtil.getEnumByDesc(PayTypeEnum.class, payName).toCode());
            userAdvance.setImportMoney(new BigDecimal(0));
            userAdvance.setExplodeMoney(money);
            userAdvance.setMemberAdvance(advance.subtract(money));
            userAdvanceService.save(userAdvance);
            //然后userWallet进行扣款
            userWalletEntity.setAdvance(advance.subtract(money));
            userWalletService.updateById(userWalletEntity);
        }
        return R.ok();
    }


    /**
     * 收银结算
     *
     * @param params
     * @return
     */

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R saveBatchReceviceMoney(Map<String, Object> params) {
        //先根据支付方式查询是否为预存款支付，为预存款则需校验余额是否够
        String payName = params.get("payName").toString();
        String memberId = params.get("memberId").toString();
        BigDecimal money = new BigDecimal(params.get("money").toString());
        String orderNos = params.get("orderNos").toString();//获取批量单号
        if (!StringUtils.isNotBlank(payName)) {
            return R.error("获取订单相关数据错误，收银失败!");
        }
        if (!StringUtils.isNotBlank(memberId)) {
            return R.error("获取订单相关数据错误，收银失败!");
        }
        if (!StringUtils.isNotBlank(orderNos)) {
            return R.error("获取订单相关数据错误，收银失败!");
        }
        if (!StringUtils.isNotBlank(payName)) {
            return R.error("获取订单相关数据错误，收银失败!");
        }
        //查询所有订单
        List<String> orderNoList= Arrays.asList(orderNos.split(","));
        List<ErpOrderEntity> erpOrderList = this.list(new QueryWrapper<ErpOrderEntity>().in("order_no",orderNoList));
        for (int i=0;i<erpOrderList.size();i++){
            ErpOrderEntity erpOrder=erpOrderList.get(i);
            //先判断订单状态是否为已完结
            if(erpOrder.getProductionStatus()==ProductionStatusEnum.FINISH.toInt()){
                return  R.error("订单"+erpOrder.getOrderNo()+"已完结，请刷新页面查看订单最新状态!");
            }
        }

        BigDecimal advance=new BigDecimal(0);
        //根据会员id去数据库查询余额
        UserWalletEntity userWalletEntity = userWalletService.getById(memberId);
        if(userWalletEntity!=null){
            advance = userWalletEntity.getAdvance();
        }
        //定义变量存储预存款所剩下金额
        BigDecimal remainMoney=advance;
        //如果是预存款支付
        if (payName.equals(PayTypeEnum.DEPOSIT.toDescribe())) {
            if (money.compareTo(advance) > 0) {
                return R.error("客户账户余额不足支付，请充值！");
            }
        }
        //添加支付单信息
        UserPaymentEntity userPayment = new UserPaymentEntity();
        // 收款单号
        String paymentId =null ;
        // 判断收款单号是否重复
        boolean repeat = true;
        do {
            paymentId= UserPaymentUtils.getPaymentsId();
            List<UserPaymentEntity> countList = userPaymentService.list(new QueryWrapper<UserPaymentEntity>().eq("payment_id", paymentId));
            if (countList == null || countList.size() <= 0) {
                repeat = false;
            }
        } while (repeat);
        userPayment.setPaymentId(paymentId);
        userPayment.setMoney(money);
        userPayment.setCurMoney(money);
        userPayment.setUserId(memberId);
        userPayment.setStatus("succ");
        userPayment.setPayName(payName);
        userPayment.setTPayed(new Date());
        userPayment.setPayType("offline");//线下支付
        userPayment.setPayAppId(EnumUtil.getEnumByDesc(PayTypeEnum.class, payName).toCode());
        //用户支付记录表;
        userPaymentService.save(userPayment);
        //流水明细
        List<UserPaymentBillEntity> userPaymentBillList=new ArrayList<>();
        //日志
        List<ErpOrderLogEntity> erpOrderLogList=new ArrayList<>();
        //批量收款记录表
        List<BatchOrderPaymentEntity> batchOrderPaymentList=new ArrayList<>();
         //用户预充值记录表
        List<UserAdvanceEntity> uerAdvanceList=new ArrayList<>();


        for (int i=0;i<erpOrderList.size();i++){
            ErpOrderEntity erpOrder=erpOrderList.get(i);
            String orderNo=erpOrder.getOrderNo();
            //如果是预存款支付则还需要操作
            //user_advance添加一条扣款记录
            //  判断false 没有扣款
            if (payName.equals(PayTypeEnum.DEPOSIT.toDescribe())) {
                    UserAdvanceEntity userAdvance = new UserAdvanceEntity();
                    userAdvance.setUserId(Integer.valueOf(memberId));
                    userAdvance.setPaymentId(userPayment.getPaymentId());
                    //订单已支付金额
                    BigDecimal payed=erpOrder.getPayed()==null?BigDecimal.ZERO:erpOrder.getPayed();
                    //当前订单支付金额
                    BigDecimal nowPaymoney=erpOrder.getPayableAmount().subtract(payed);
                    userAdvance.setMoney(nowPaymoney);
                    remainMoney=remainMoney.subtract(nowPaymoney);
                    userAdvance.setMessage("门店批量收款支付订单");
                    userAdvance.setMtime(new Date());
                    userAdvance.setOrderId(Long.valueOf(orderNo));
                    userAdvance.setPaymethod(EnumUtil.getEnumByDesc(PayTypeEnum.class, payName).toCode());
                    userAdvance.setImportMoney(new BigDecimal(0));
                    userAdvance.setExplodeMoney(nowPaymoney);
                    userAdvance.setMemberAdvance(remainMoney);
                    uerAdvanceList.add(userAdvance);
                }
            //判断是否为自提，如果为自提，则收银结算将发货状态和收货状态更改为已收货
            if (erpOrder.getSendType() == SendTypeEnum.PICK_UP.toInt()) {
                //1为已发货
                erpOrder.setShipStatus(1);
                erpOrder.setReceivedStatus(ReceivedStatusEnum.RECEIVED.toInt());
                erpOrder.setReceivedTime(new Date());
            }
            erpOrder.setPayment(payName);
            erpOrder.setPayStatus(Integer.valueOf(PayStatusEnum.ALREADY_PAY_1.toCode()));
            erpOrder.setProductionStatus(ProductionStatusEnum.FINISH.toInt());
            erpOrder.setPaymentTime(new Date());
            erpOrder.setPaymentId(userPayment.getPaymentId());
            erpOrder.setLastModifiedTime(new Date());
            erpOrder.setIsUrgent(0);

            // 订单，支付单关联信息
            UserPaymentBillEntity userPaymentBill = new UserPaymentBillEntity();
            userPaymentBill.setRelId(Long.valueOf(orderNo));
            userPaymentBill.setBillId(userPayment.getPaymentId());
            userPaymentBill.setPayObject(PayObjectEnum.ORDER.toCode());
            userPaymentBill.setBillType(BillTypeEnum.PAYMENTS.toCode());
            BigDecimal payed=erpOrder.getPayed()==null?BigDecimal.ZERO:erpOrder.getPayed();
            BigDecimal payAmount=erpOrder.getPayableAmount().subtract(payed);
            userPaymentBill.setMoney(payAmount);
            userPaymentBillList.add(userPaymentBill);
            //注意顺序
            erpOrder.setPayed(erpOrder.getPayableAmount());

            BatchOrderPaymentEntity batchOrderPayment=new BatchOrderPaymentEntity();
            batchOrderPayment.setPaymentTime(new Date());
            batchOrderPayment.setStatus("succ");
            batchOrderPayment.setOrderNo(orderNo);
            batchOrderPayment.setPaymentId(paymentId);
            batchOrderPayment.setDel(false);
            batchOrderPaymentList.add(batchOrderPayment);
            //创建erp_order_log
            ErpOrderLogEntity erpOrderLog = new ErpOrderLogEntity();
            erpOrderLog.setOrderNo(orderNo);
            erpOrderLog.setCreateName(UserUtils.getCurentUser().getUsername());
            erpOrderLog.setCreateTime(new Date());
            erpOrderLog.setCreateBy(UserUtils.getCurentUser().getSellerId().toString());
            erpOrderLog.setLogText("门店批量收款"+orderNos);
            erpOrderLogList.add(erpOrderLog);
        }

        //批量修改订单信息
        if(erpOrderList.size()>0){
            this.updateBatchById(erpOrderList);
        }
        if(userPaymentBillList.size()>0){
            userPaymentBillService.saveBatch(userPaymentBillList);
        }
        if(batchOrderPaymentList.size()>0){
            batchOrderPaymentService.saveBatch(batchOrderPaymentList);
        }
        if(erpOrderLogList.size()>0){
            erpOrderLogService.saveBatch(erpOrderLogList);
        }
        if(uerAdvanceList.size()>0){
            userAdvanceService.saveBatch(uerAdvanceList);
        }
        //预存款扣款
        if (payName.equals(PayTypeEnum.DEPOSIT.toDescribe())) {
            userWalletEntity.setAdvance(advance.subtract(money));
            userWalletService.updateById(userWalletEntity);
        }
        // 同步更新 order_info 支付信息，门店订单直接更新订单完结状态，商城订单交由计划任务处理
        List<OrderInfoEntity> orderInfoList=orderInfoService.list(new QueryWrapper<OrderInfoEntity>().in("order_id",orderNoList));
        for (int i=0;i<orderInfoList.size();i++){
            OrderInfoEntity orderInfo = orderInfoList.get(i);
            if (orderInfo != null) {
                Map<String, Object> updateMap = new HashMap<>();
                for (int j=0;j<erpOrderList.size();j++){
                    ErpOrderEntity erpOrder = erpOrderList.get(j);
                    if(erpOrder.getOrderNo().equals(orderInfo.getOrderId())){
                        String source = orderInfo.getSource();
                        if (StringUtils.equals(source, "erp")) {
                            orderInfo.setStatus(OrderInfoStatusEnum.FINISH.toCode());
                        }
                        orderInfo.setPayableAmount(erpOrder.getPayableAmount());
                        orderInfo.setPayed(erpOrder.getPayed());
                        orderInfo.setPayStatus(erpOrder.getPayStatus().toString());
                    }
                }
            }
        }
        //修改orderInfo信息
        if(orderInfoList.size()>0){
            orderInfoService.updateBatchById(orderInfoList);
        }
        return R.ok();
    }



    /**
     * 批量扫码支付时调用的业务代码
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void receiveMoneyByCode(Map<String, Object> params){
        String payName = params.get("payName").toString();
        String paymentId = params.get("paymentId").toString();
        BigDecimal money = new BigDecimal(params.get("money").toString());
        String orderNo = params.get("orderNo").toString();
        //收款成功后，更改订单状态为已完结,已支付
        ErpOrderEntity erpOrder = this.getById(orderNo);

        //判断是否为自提，如果为自提，则收银结算将发货状态和收货状态更改为已收货
        if (erpOrder.getSendType() == SendTypeEnum.PICK_UP.toInt()) {
            //1为已发货
            erpOrder.setShipStatus(1);
            erpOrder.setReceivedStatus(ReceivedStatusEnum.RECEIVED.toInt());
            erpOrder.setReceivedTime(new Date());
        }
        // 修改已支付金额
        BigDecimal payed = erpOrder.getPayed().add(money);
        // 抹零金额添加至调价
        BigDecimal discount = erpOrder.getDiscount();
        BigDecimal payableAmount = erpOrder.getPayableAmount();
        BigDecimal subtract = payed.subtract(payableAmount);
        discount = subtract.add(discount);
        erpOrder.setDiscount(discount);
        erpOrder.setPayableAmount(payed);
        erpOrder.setPayed(payed);
        erpOrder.setPayment(payName);
        erpOrder.setPayStatus(Integer.valueOf(PayStatusEnum.ALREADY_PAY_1.toCode()));
        erpOrder.setProductionStatus(ProductionStatusEnum.FINISH.toInt());
        erpOrder.setPaymentTime(new Date());
        erpOrder.setPaymentId(paymentId);
        erpOrder.setLastModifiedTime(new Date());
        erpOrder.setIsUrgent(0);
        this.updateById(erpOrder);

        // 同步更新 order_info 支付信息，门店订单直接更新订单完结状态，商城订单交由计划任务处理
        OrderInfoEntity orderInfo = orderInfoService.getById(orderNo);
        if (orderInfo != null) {
            Map<String, Object> updateMap = new HashMap<>();
            String source = orderInfo.getSource();
            if (StringUtils.equals(source, "erp")) {
                updateMap.put("status", OrderInfoStatusEnum.FINISH.toCode());
            }
            updateMap.put("discount", erpOrder.getDiscount());
            updateMap.put("payableAmount", erpOrder.getPayableAmount());
            updateMap.put("payed", erpOrder.getPayed());
            updateMap.put("payStatus", erpOrder.getPayStatus().toString());
            orderInfoService.updateByMap(updateMap, orderNo);
        }
        //创建erp_order_log
        ErpOrderLogEntity erpOrderLog = new ErpOrderLogEntity();
        erpOrderLog.setOrderNo(orderNo);
        erpOrderLog.setCreateName(UserUtils.getCurentUser().getUsername());
        erpOrderLog.setCreateTime(new Date());
        erpOrderLog.setCreateBy(UserUtils.getCurentUser().getSellerId().toString());
        erpOrderLog.setLogText("门店扫码收款");
        erpOrderLogService.save(erpOrderLog);
    }


    /**
     * 扫码支付时调用的业务代码
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void bacthReceiveMoneyByCode(Map<String, Object> params){
        String payName = params.get("payName").toString();
        String paymentId = params.get("paymentId").toString();
        BigDecimal money = new BigDecimal(params.get("money").toString());
        String orderNos = params.get("orderNos").toString();
        List<String> orderNoList=Arrays.asList(orderNos.split(","));

        List<ErpOrderEntity> orderList=this.list(new QueryWrapper<ErpOrderEntity>().in("order_no",orderNoList));
        //日志集合
        List<ErpOrderLogEntity> erpOrderLoglist=new ArrayList<>();
        for (int i=0;i<orderList.size();i++){
            //收款成功后，更改订单状态为已完结,已支付
            ErpOrderEntity erpOrder = orderList.get(i);
            //判断是否为自提，如果为自提，则收银结算将发货状态和收货状态更改为已收货
            if (erpOrder.getSendType() == SendTypeEnum.PICK_UP.toInt()) {
                //1为已发货
                erpOrder.setShipStatus(1);
                erpOrder.setReceivedStatus(ReceivedStatusEnum.RECEIVED.toInt());
                erpOrder.setReceivedTime(new Date());
            }
            //查询之前已支付金额
            // 修改已支付金额
            erpOrder.setPayed(erpOrder.getPayableAmount());
            erpOrder.setPayment(payName);
            erpOrder.setPayStatus(Integer.valueOf(PayStatusEnum.ALREADY_PAY_1.toCode()));
            erpOrder.setProductionStatus(ProductionStatusEnum.FINISH.toInt());
            erpOrder.setPaymentTime(new Date());
            erpOrder.setPaymentId(paymentId);
            erpOrder.setLastModifiedTime(new Date());
            erpOrder.setIsUrgent(0);
            //创建erp_order_log
            ErpOrderLogEntity erpOrderLog = new ErpOrderLogEntity();
            erpOrderLog.setOrderNo(erpOrder.getOrderNo());
            erpOrderLog.setCreateName(UserUtils.getCurentUser().getUsername());
            erpOrderLog.setCreateTime(new Date());
            erpOrderLog.setCreateBy(erpOrder.getThirdMerchantId().toString());
            erpOrderLog.setLogText("门店结算单扫码收款");
            erpOrderLoglist.add(erpOrderLog);
        }
        if(orderList.size()>0){
            this.updateBatchById(orderList);
        }


        // 同步更新 order_info 支付信息，门店订单直接更新订单完结状态，商城订单交由计划任务处理
        List<OrderInfoEntity> orderInfoList=orderInfoService.list(new QueryWrapper<OrderInfoEntity>().in("order_id",orderNoList));
        for (int i=0;i<orderInfoList.size();i++){
            OrderInfoEntity orderInfo = orderInfoList.get(i);
            if (orderInfo != null) {
                Map<String, Object> updateMap = new HashMap<>();
                for (int j=0;j<orderList.size();j++){
                    ErpOrderEntity erpOrder = orderList.get(j);
                    if(erpOrder.getOrderNo().equals(orderInfo.getOrderId())){
                        String source = orderInfo.getSource();
                        if (StringUtils.equals(source, "erp")) {
                            orderInfo.setStatus(OrderInfoStatusEnum.FINISH.toCode());
                        }
                        orderInfo.setDiscount( erpOrder.getDiscount());
                        orderInfo.setPayableAmount(erpOrder.getPayableAmount());
                        orderInfo.setPayed(erpOrder.getPayed());
                        orderInfo.setPayStatus(erpOrder.getPayStatus().toString());
                    }
                }
            }
        }
        //修改orderInfo信息
        if(orderInfoList.size()>0){
            orderInfoService.updateBatchById(orderInfoList);
        }
        if(erpOrderLoglist.size()>0){
            erpOrderLogService.saveBatch(erpOrderLoglist);
        }
    }


    //修改订单
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R updateByOrderNo(ErpOrderItemDto erpOrderItemDto) {
        ErpOrderEntity erpOrder = erpOrderItemDto.getErpOrder();
        ValidatorUtils.validateEntity(erpOrder);

        //查询storeMember表是否存在此客户
        StoreMemberEntity storeMemberEntity = storeMemberService.getOne(new QueryWrapper<StoreMemberEntity>().eq("member_id", erpOrder.getMemberId()));
        //商户id
        Long sellerId = UserUtils.getCurentUser().getSellerId();

        //更改后的商品详情
        List<ErpOrderItemEntity> erpOrderItemList = erpOrderItemDto.getErpOrderItemList();
        String orderNo = erpOrder.getOrderNo();
        if (!StringUtils.isNotBlank(orderNo)) {
            return R.error("修改订单信息失败");
        } else {
            /*
                1.删除之前的订单商品详情
                2.增加修改后的订单
                3.添加订单修改日志
             */
            //删除
            erpOrderItemService.remove(new QueryWrapper<ErpOrderItemEntity>().eq("order_no", orderNo));
            //更改订单以及相关信息
            //遍历订单详情集合获取订单总金额
            BigDecimal totalAmount = new BigDecimal(0);
            //总价=价格*数量,商品总值
            for (int i = 0; i < erpOrderItemList.size(); i++) {
                BigDecimal returnedMoney = erpOrderItemList.get(i).getAmount();
                totalAmount = totalAmount.add(returnedMoney);
            }
            erpOrder.setTotalAmount(totalAmount);
            //定义变量用于统计优惠后的总金额
            BigDecimal payableAmount = new BigDecimal(0);
            for (int i = 0; i < erpOrderItemList.size(); i++) {
                ErpOrderItemEntity erpOrderItem = erpOrderItemList.get(i);
                erpOrderItem.setOrderNo(orderNo);
                BigDecimal amount = new BigDecimal(0);
                //如果不是标品，则需要用非标品计算价格
                if (!erpOrderItem.getAddcartBuyType().equals("standard")) {
                    //先根据productId从goods表中获取goods_id
                    List<GoodsEntity> goodsList = goodsService.list(new QueryWrapper<GoodsEntity>().eq("category_id", erpOrderItem.getProductId())
                            .eq("date_flag", 0).notIn("marketable", "delete"));
                    if (goodsList.size() != 1) {
                        throw new RRException("修改订单失败");
                    } else {
                        GoodsEntity goodsEntity = goodsList.get(0);
                        erpOrderItem.setName(goodsEntity.getName());
                        erpOrderItem.setGoodsId(goodsEntity.getGoodsId().intValue());
                        //当计算错误或未找到优惠，则返回0
                        amount = getNotStandardTotalAmount(erpOrderItem, storeMemberEntity);
                        if (amount.compareTo(new BigDecimal(0)) == 0) {
                            amount = erpOrderItem.getAmount();
                        }
                    }
                } else {
                    //判断门店是否存在对应商品的优惠
                    StoreProductPriceEntity storeProductPrice = storeProductPriceService.getOne(new QueryWrapper<StoreProductPriceEntity>().eq("product_id", erpOrderItem.getProductId())
                            .eq("seller_id", sellerId));
                    if (storeProductPrice == null) {
                        amount = erpOrderItem.getNums().multiply(erpOrderItem.getPrice());
                    } else {
                        amount = getTotalAmount(erpOrderItem, storeMemberEntity);
                    }
                }
                erpOrderItem.setAmount(amount);
                //统计应付金额
                BigDecimal total = payableAmount.add(amount);
                payableAmount = total;
                erpOrderItem.setItemDel(0);
                erpOrderItem.setItemType(OrderItemTypeEnum.PRODUCT.toCode());
                //待分配
                erpOrderItem.setStatus(OrderItemStatusEnum.UN_ALLOTED.toInt());
            }
            //应付金额
            erpOrder.setPayableAmount(payableAmount.setScale(2,BigDecimal.ROUND_DOWN));
            //优惠金额
            BigDecimal pmtGoods = erpOrder.getTotalAmount().subtract(erpOrder.getPayableAmount());
            erpOrder.setPmtGoods(pmtGoods);
            //更新应付金额
            this.saveOrUpdate(erpOrder);
            if (erpOrderItemList.size() > 0) {
                erpOrderItemService.saveBatch(erpOrderItemList);
            }

            //添加操作日志
            ErpOrderLogEntity erpOrderLogEntity = new ErpOrderLogEntity();
            erpOrderLogEntity.setOrderNo(orderNo);
            erpOrderLogEntity.setCreateName(UserUtils.getCurentUser().getUsername());
            erpOrderLogEntity.setCreateBy(UserUtils.getCurentUser().getSellerId().toString());
            erpOrderLogEntity.setLogText("修改订单商品列表");
            erpOrderLogService.save(erpOrderLogEntity);
            return R.ok();
        }
    }

    //修改支付方式
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R updatePayType(ErpOrderEntity erpOrder) {
        //先查询之前支付方式
        ErpOrderEntity erpOrderEntity = this.getById(erpOrder);
        //支付单号
        String paymentId = erpOrderEntity.getPaymentId();
        //先获取当前支付方式
        String paymentNow = erpOrderEntity.getPayment();
        //获取客户账户
        UserWalletEntity userWalletEntity = userWalletService.getByUserId(erpOrderEntity.getMemberId());
        //如果当前支付方式为预存款，修改为其他方式，则需将已支付金额退还到客户账户中
        // 将之
        if(paymentNow.equals("预存款支付")){
            BigDecimal walladvace = userWalletEntity.getAdvance();
            BigDecimal erpOPayed = erpOrderEntity.getPayed();
            BigDecimal ReturnMoney = walladvace.add(erpOPayed);
            UserAdvanceEntity userAdvance = new UserAdvanceEntity();
            userAdvance.setUserId(Integer.valueOf(erpOrderEntity.getMemberId()));
            userAdvance.setPaymentId(paymentId);
            userAdvance.setMoney(erpOPayed);
            userAdvance.setMessage("修改支付方式退款");
            userAdvance.setMtime(new Date());
            userAdvance.setOrderId(Long.valueOf(erpOrderEntity.getOrderNo()));
            userAdvance.setPaymethod(EnumUtil.getEnumByDesc(PayTypeEnum.class, erpOrder.getPayment()).toCode());
            userAdvance.setImportMoney(erpOPayed);
            userAdvance.setExplodeMoney(new BigDecimal(0));
            userAdvance.setMemberAdvance(ReturnMoney);
            userAdvanceService.save(userAdvance);
            int i = userWalletService.updateByUserId(erpOrderEntity.getMemberId(), ReturnMoney);
            if (i != 1) {
                return R.error("支付方式变更失败");
            }
        }
        //如果修改为预存款支付
        if(erpOrder.getPayment().equals("预存款支付")){
            BigDecimal walladvace = userWalletEntity.getAdvance();
            BigDecimal erpOPayed = erpOrderEntity.getPayed();
            BigDecimal  returnMoney = walladvace.subtract(erpOPayed);
            if(returnMoney.compareTo(new BigDecimal(0))<0){
                return R.error("客户余额小于待支付金额，请充值!");
            }
            UserAdvanceEntity userAdvance = new UserAdvanceEntity();
            userAdvance.setUserId(Integer.valueOf(erpOrderEntity.getMemberId()));
            userAdvance.setPaymentId(paymentId);
            userAdvance.setMoney(erpOPayed);
            userAdvance.setMessage("门店修改支付方式收款");
            userAdvance.setMtime(new Date());
            userAdvance.setOrderId(Long.valueOf(erpOrderEntity.getOrderNo()));
            userAdvance.setPaymethod(EnumUtil.getEnumByDesc(PayTypeEnum.class, erpOrder.getPayment()).toCode());
            userAdvance.setImportMoney( new BigDecimal(0)) ;
            userAdvance.setExplodeMoney(erpOPayed);
            userAdvance.setMemberAdvance(returnMoney);
            userAdvanceService.save(userAdvance);
            int i = userWalletService.updateByUserId(erpOrderEntity.getMemberId(), returnMoney);
            if (i != 1) {
                return R.error("支付方式变更失败");
            }
        }
        //根据支付单号去userPayment中查询支付信息
        UserPaymentEntity userPaymentEntity = userPaymentService.getById(paymentId);
        userPaymentEntity.setPayName(erpOrder.getPayment());
        userPaymentEntity.setTPayed(new Date());
        userPaymentEntity.setOpId(UserUtils.getCurentUser().getUsername());
        //修改支付表
        userPaymentService.updateById(userPaymentEntity);
        //修改支付方式
        erpOrderEntity.setPayment(erpOrder.getPayment());
        this.updateById(erpOrderEntity);
        //添加日志
        ErpOrderLogEntity erpOrderLogEntity = new ErpOrderLogEntity();
        erpOrderLogEntity.setCreateName(UserUtils.getCurentUser().getUsername());
        erpOrderLogEntity.setCreateTime(new Date());
        erpOrderLogEntity.setOrderNo(erpOrder.getOrderNo());
        erpOrderLogEntity.setLogText("原支付方式为"+paymentNow+"，修改支付方式为:" + erpOrder.getPayment());
        erpOrderLogService.save(erpOrderLogEntity);
        return R.ok();
    }

    /**
     * 订单撤回
     * 生产完成-》生产中-》新开单
     */
    @Override
    public R orderRecall(String orderNo) {
        //添加日志
        ErpOrderLogEntity erpOrderLog = new ErpOrderLogEntity();
        //先根据订单号判断订单的生产状态
        ErpOrderEntity erpOrderEntity = this.getById(orderNo);
        //先判断是否为紫云网分配过来的订单
        if (erpOrderEntity.getSource().equals("1")) {
            return R.error("紫云网订单无法撤回!");
        }
        //如果当前状态为生产完成
        if (erpOrderEntity.getProductionStatus() == ProductionStatusEnum.PRODUCTION_FINISH.toInt()) {
            //修改状态为生产中
            erpOrderEntity.setProductionStatus(ProductionStatusEnum.IN_PRODUCTION.toInt());
            erpOrderLog.setLogText("门店订单撤回：订单状态由生产完成状态撤回为生产中状态");
        } else if (erpOrderEntity.getProductionStatus() == ProductionStatusEnum.IN_PRODUCTION.toInt()) {
            //如果当前状态为生产中.修改为新开单
            erpOrderEntity.setProductionStatus(ProductionStatusEnum.NEW_ORDER.toInt());
            erpOrderLog.setLogText("门店订单撤回：订单状态由生产中状态撤回为新开单状态");
        } else {
            return R.error("请选择生产状态为生产中或生产完成的订单!");
        }
        //状态进行回撤
        this.updateById(erpOrderEntity);
        erpOrderLog.setOrderNo(orderNo);
        erpOrderLog.setCreateName(UserUtils.getCurentUser().getUsername());
        erpOrderLog.setCreateTime(new Date());
        erpOrderLogService.save(erpOrderLog);
        return R.ok();
    }

    @Override
    public R orderUrgent(String orderNo) {
        //先根据订单号判断订单是否已完结，完结则不更改加急状态
        //6.已完成;11.已作废，4,生产完成
        ErpOrderEntity erpOrderEntity = this.getById(orderNo);

        //添加日志
        ErpOrderLogEntity erpOrderLog = new ErpOrderLogEntity();

        if (erpOrderEntity.getProductionStatus() == ProductionStatusEnum.FINISH.toInt()) {
            return R.error("已完成订单无需修改加急状态");
        }
        if (erpOrderEntity.getProductionStatus() == 4) {
            return R.error("已生产完成订单无法修改加急状态");
        } else if (erpOrderEntity.getProductionStatus() == 11) {
            return R.error("已作废订单无需修改加急状态");
        } else {
            int isUrgent = erpOrderEntity.getIsUrgent();
            if (isUrgent == 0) {
                erpOrderEntity.setIsUrgent(1);
                erpOrderLog.setLogText("修改订单为加急状态");
            } else {
                erpOrderEntity.setIsUrgent(0);
                erpOrderLog.setLogText("取消订单的加急状态");
            }
            //跟新数据
            this.updateById(erpOrderEntity);
            erpOrderLog.setOrderNo(orderNo);
            erpOrderLog.setCreateName(UserUtils.getCurentUser().getUsername());
            erpOrderLog.setCreateTime(new Date());
            erpOrderLogService.save(erpOrderLog);
            return R.ok();
        }
    }

    /**
     * 修改订单状态
     *
     * @param orderNo
     * @param status
     * @return
     */
    @Override
    public R updateStatus(String orderNo, Integer status) {
        ErpOrderEntity erpOrderEntity = new ErpOrderEntity();
        erpOrderEntity.setOrderNo(orderNo);
        erpOrderEntity.setProductionStatus(status);
        try {
            this.updateById(erpOrderEntity);
        } catch (Exception e) {
            return R.error("修改订单状态失败");
        }

        // 若是紫云网分配订单，需要关联更新生产单信息
        if (status.intValue() == 3){
            ErpOrderProductionEntity erpOrderProduction = erpOrderProductionService.getOne(new QueryWrapper<>(new ErpOrderProductionEntity()).eq("production_order", orderNo));
            if (erpOrderProduction != null){
                String orderId = erpOrderProduction.getOrderNo();
                ErpOrderEntity erpOrder = this.getById(orderId);
                Integer thirdMerchantId = erpOrder.getThirdMerchantId();
                if (thirdMerchantId.intValue() == 1){
                    Map<String, Object> updateMap = new HashMap<>();
                    updateMap.put("productionStatus", OrderProductionStatusEnum.PRODUCING.toInt());
                    erpOrderProductionService.updateByMap(updateMap, erpOrderProduction.getProductionId());
                }
            }
        }

        ErpOrderLogEntity erpOrderLogEntity = new ErpOrderLogEntity();
        erpOrderLogEntity.setCreateName(UserUtils.getCurentUser().getUsername());
        erpOrderLogEntity.setCreateTime(new Date());
        erpOrderLogEntity.setLogText("修改订单状态:" + EnumUtil.getEnumByCodeInt(ProductionStatusEnum.class, status.intValue()).toDescribe());
        return R.ok();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R finishOrderItem(String orderNo) {
        //先根据订单号判断订单的生产状态
        ErpOrderEntity erpOrderEntity = this.getById(orderNo);
        //根据订单号查询是否有至少一个商品，如没商品，不允许生产完成
       List<ErpOrderItemEntity> itemList= erpOrderItemService.list(new QueryWrapper<ErpOrderItemEntity>().eq("order_no",orderNo).eq("item_del",0));
       if(itemList.size()==0){
           return R.error("请至少添加一个商品后再进行生产完成操作！");
       }
        //7为新开单，3为生产中
        if (erpOrderEntity.getProductionStatus() != ProductionStatusEnum.NEW_ORDER.toInt() && erpOrderEntity.getProductionStatus() != ProductionStatusEnum.IN_PRODUCTION.toInt()) {
            return R.error("当前订单不是新开订单或生产中订单");
        } else {
            //4为生产完成
            erpOrderEntity.setProductionStatus(ProductionStatusEnum.PRODUCTION_FINISH.toInt());
           /* //加急状态改成普通的
            erpOrderEntity.setIsUrgent(0);*/
           //判断订单是否已经支付，并且不是紫云网分配过来的
            //加急状态改成普通的
            erpOrderEntity.setIsUrgent(0);
            //更改状态
            this.updateById(erpOrderEntity);

            // 查询是否紫云网分配订单，需要关联更新生产单信息
            ErpOrderProductionEntity erpOrderProduction = erpOrderProductionService.getOne(new QueryWrapper<>(new ErpOrderProductionEntity()).eq("production_order", orderNo));
            if (erpOrderProduction != null){
                String orderId = erpOrderProduction.getOrderNo();
                ErpOrderEntity erpOrder = this.getById(orderId);
                Integer thirdMerchantId = erpOrder.getThirdMerchantId();
                if (thirdMerchantId.intValue() == 1){
                    Map<String, Object> updateMap = new HashMap<>();
                    updateMap.put("productionStatus", OrderProductionStatusEnum.FINISH.toInt());
                    erpOrderProductionService.updateByMap(updateMap, erpOrderProduction.getProductionId());
                }
            }

            //添加日志
            ErpOrderLogEntity erpOrderLog = new ErpOrderLogEntity();
            erpOrderLog.setOrderNo(orderNo);
            erpOrderLog.setCreateName(UserUtils.getCurentUser().getUsername());
            erpOrderLog.setLogText("修改订单状态为生产完成");
            erpOrderLog.setCreateTime(new Date());
            erpOrderLogService.save(erpOrderLog);
        }
        return R.ok();
    }

    //获取日志信息
    @Override
    public R getErpOrderLog(String orderNo) {
        List<ErpOrderLogEntity> erpOrderLogData = erpOrderLogService.list(new QueryWrapper<ErpOrderLogEntity>().eq("order_no", orderNo));
        return R.ok().put("erpOrderLogData", erpOrderLogData);
    }

    /**
     * 标品分配找工厂
     *
     * @param eoItemId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R orderItemAllotFindFactory(Integer eoItemId) {
        //先查询erpOrder数据封装到OrderInfo
        //查询erp_order_item数据封装到orderItem;
        ErpOrderItemEntity erpOrderItemEntity = erpOrderItemService.getById(eoItemId);
        String orderNo = erpOrderItemEntity.getOrderNo();
        ErpOrderProductionEntity erpOrderProduction = erpOrderProductionService.getOne(new QueryWrapper<ErpOrderProductionEntity>()
                .eq("order_no", orderNo).eq("del", 0).eq("erp_item_id",eoItemId)
                .notIn("allot_type",AllotTypeEnum.ORDER.toCode()).notIn("production_status",4));
        if(erpOrderProduction!=null){
            if(!erpOrderProduction.getAllotType().equals(ProducerTypeEnum.ZIYUN_SUPPLIER)){
                return  R.error("已分配商品无需再次分配!");
            }
        }
        // 分配至第三方
        logger.info("================= standard item find factory api start==================");
        MultyErpOrderParam multyErpOrderParam = new MultyErpOrderParam();
        multyErpOrderParam.setAllotOrderId(orderNo.toString());
        multyErpOrderParam.setGoodsSplitType(com.service.common.constant.GoodsSplitType.standardGoods);
        multyErpOrderParam.setOrderItemId(erpOrderItemEntity.getOriginalItemId());
        SellerInfoEntity sellerInfoEntity = sellerInfoService.getById(UserUtils.getCurentUser().getSellerId());
        //判断是自营门店还是第三方供应商
        if(sellerInfoEntity.getSelf()==1){
            multyErpOrderParam.setOrderSplitType(OrderSplitType.self_shop);
        }else{
            multyErpOrderParam.setOrderSplitType(OrderSplitType.third_supplier);
        }
        logger.info("================= 标品分配找工厂请求参数：" + JsonUtils.object2String(multyErpOrderParam));
        GoodsResult<?> goodsForOrderErp = goodsAlloteService.getGoodsForOrderErp(multyErpOrderParam);
        int code = goodsForOrderErp.getCode();
        if (code != 1) {
            return R.error(goodsForOrderErp.getMessage());
        }
        List<BaseGoodsInfoVO> goodsInfoVOList = (List<BaseGoodsInfoVO>) goodsForOrderErp.getData();
        return R.ok().put("factoryInfosQuery", goodsInfoVOList);
    }


    //报价商品分配找工厂
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R quoteOrderItemAllotFindFactory(Integer eoItemId) {
        //先查询出erp_order_item
        ErpOrderItemEntity erpOrderItemEntity = erpOrderItemService.getById(eoItemId);
        String orderNo = erpOrderItemEntity.getOrderNo();
        ErpOrderProductionEntity erpOrderProduction = erpOrderProductionService.getOne(new QueryWrapper<ErpOrderProductionEntity>()
                .eq("order_no", orderNo).eq("del", 0).eq("erp_item_id",eoItemId)
                .notIn("allot_type",AllotTypeEnum.ORDER.toCode()).notIn("production_status",4));
        if(erpOrderProduction!=null){
            if(!erpOrderProduction.getAllotType().equals(ProducerTypeEnum.ZIYUN_SUPPLIER)){
                return  R.error("已分配商品无需再次分配!");
            }
        }
        Integer itemId = erpOrderItemEntity.getOriginalItemId();
        OrderItemEntity orderItem = orderItemService.getById(itemId);

        MultyErpOrderParam multyErpOrderParam = new MultyErpOrderParam();
        multyErpOrderParam.setAllotOrderId(orderItem.getOrderId().toString());
        multyErpOrderParam.setGoodsSplitType(GoodsSplitType.quoteGoods);
        multyErpOrderParam.setOrderItemId(itemId);
        SellerInfoEntity sellerInfoEntity = sellerInfoService.getById(UserUtils.getCurentUser().getSellerId());
        //判断是自营门店还是第三方供应商
        if(sellerInfoEntity.getSelf()==1){
            multyErpOrderParam.setOrderSplitType(OrderSplitType.self_shop);
        }else{
            multyErpOrderParam.setOrderSplitType(OrderSplitType.third_supplier);
        }
        logger.info("================= quote item find factory api param：" + JsonUtils.object2String(multyErpOrderParam));
        GoodsResult<?> goodsForOrderErp = goodsAlloteService.getGoodsForOrderErp(multyErpOrderParam);
        int code = goodsForOrderErp.getCode();
        if (code != 1) {
            return R.error(goodsForOrderErp.getMessage());
        }
        LinkedHashMap result = (LinkedHashMap) goodsForOrderErp.getData();
        // 符合报价产品的条件的工厂详情
        List<com.service.quote.module.factory.model.FactoryQuoteInfo> factoryQuoteInfos = (List<FactoryQuoteInfo>) result.get("factoryQuoteInfos");
        // 报价产品的相关信息 todo 解析有问题
//        QuoteProductResultVO productVO = (QuoteProductResultVO) result.get("productVO");
        // 报价产品参数
        String quoteProductDetail = (String) result.get("quoteProductDetail");
        return R.ok().put("factoryQuoteInfos", factoryQuoteInfos);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public R allotOrderItem(OrderItemAllotDto orderItemAllotDto) {
        String orderNo = orderItemAllotDto.getOrderNo();
        boolean allotFlag = this.isAllot(orderNo);
        if(allotFlag){
            return R.error("紫云网分配订单不允许再次分配!");
        }
        ErpOrderEntity erpOrderEntity = this.getById(orderNo);
        Integer erpItemId = orderItemAllotDto.getErpItemId();
        Integer userId = orderItemAllotDto.getUserId();
        Integer producer = orderItemAllotDto.getProducer();
        BigDecimal cost = orderItemAllotDto.getCost();
        Boolean self = orderItemAllotDto.getSelf();

        ErpOrderItemEntity erpOrderItem = erpOrderItemService.getById(erpItemId);
        if (erpOrderItem.getStatus().intValue() != OrderItemStatusEnum.UN_ALLOTED.toInt()) {
            return R.error("商品状态异常！");
        }

        int count = erpOrderProductionService.count(new QueryWrapper<>(new ErpOrderProductionEntity())
                .eq("order_no", orderNo)
                .eq("erp_item_id", erpItemId)
                .eq("del", DeleteEnum.NOT_DELETE.toInt())
                .notIn("production_status", OrderProductionStatusEnum.CANCLE.toInt())
        );
        if (count > 0) {
            return R.error("商品已存在分配信息！");
        }
        //商品类型
        String addcartBuyType = erpOrderItem.getAddcartBuyType();
        boolean quoteType = StringUtils.equals(addcartBuyType, "fast") || StringUtils.equals(addcartBuyType, "print");
        Integer itemId = erpOrderItem.getOriginalItemId();
        OrderResult<AllotOrderResultDto> allotOrderResultDtoOrderResult = requestItemAllotQuoteApi(orderNo, itemId, self, producer, quoteType);
        if (allotOrderResultDtoOrderResult == null) {
            return R.error("调用接口服务失败！");
        }
        int code = allotOrderResultDtoOrderResult.getCode();
        if (code != 1) {
            return R.error(allotOrderResultDtoOrderResult.getMessage());
        }
        AllotOrderResultDto allotOrderResultDto = allotOrderResultDtoOrderResult.getData();
        List<OldItemNew> itemList = allotOrderResultDto.getItemList();
        OldItemNew oldItemNew = itemList.get(0);
        saveItemAllotQuote(orderNo, erpOrderItem, cost, producer, oldItemNew);

        //修改erpOrderItem状态
        ErpOrderItemEntity erpOrderItemEntity = erpOrderItemService.getById(erpItemId);
        //2为生产中
        erpOrderItemEntity.setStatus(2);
        erpOrderItemService.updateById(erpOrderItemEntity);
        return R.ok();
    }

    /**
     * 商品分配：报价商品分配后保存生产单信息
     */
    public void saveItemAllotQuote(String orderNo, ErpOrderItemEntity erpOrderItem, BigDecimal cost, int producer, OldItemNew oldItemNew) {
        int oldItemId = oldItemNew.getOldItemId();
        String newOrderId = oldItemNew.getNewOrderId();
        int newItemId = oldItemNew.getNewItemId();

        // 保存生产单信息
        ErpOrderProductionEntity erpOrderProduction = new ErpOrderProductionEntity();
        erpOrderProduction.setOrderNo(orderNo);
        erpOrderProduction.setAllotType("goods");
        erpOrderProduction.setErpItemId(erpOrderItem.getEoItemId().toString());
        erpOrderProduction.setOrderItemId(erpOrderItem.getOriginalItemId().toString());
        erpOrderProduction.setAddon(erpOrderItem.getAddon());
        erpOrderProduction.setUnit(erpOrderItem.getUnit());
        erpOrderProduction.setNums(erpOrderItem.getNums());
        erpOrderProduction.setCost(cost);
        if(cost.compareTo(new BigDecimal(0))>0){
            erpOrderProduction.setCostStatus(true);
        }else{
            erpOrderProduction.setCostStatus(false);
        }
        erpOrderProduction.setProducer(producer);
        //根据producer查询生产商名称
        SellerInfoEntity seller = sellerInfoService.getById(producer);
        erpOrderProduction.setProducerName(seller.getSellerName());
        erpOrderProduction.setCreateName(UserUtils.getCurentUser().getUserId().toString());
        erpOrderProduction.setOnlineCash(1);
        erpOrderProduction.setProducerType(ProducerTypeEnum.QUOTE_FACTORY.toInt());
        erpOrderProduction.setProductionOrder(newOrderId);
        //直接置为生产完成
        erpOrderProduction.setProductionStatus(OrderProductionStatusEnum.FINISH.toInt());
        erpOrderProductionService.save(erpOrderProduction);
        // 保存分配关系
        ErpOrderAllotRelevanceEntity relevanceEntity = new ErpOrderAllotRelevanceEntity();
        relevanceEntity.setOriginalOrderNo(orderNo);
        relevanceEntity.setOrderAllotNo(newOrderId);
        relevanceEntity.setProductionId(erpOrderProduction.getProductionId());
        relevanceEntity.setOriginalItemId(oldItemId);
        relevanceEntity.setItemAllotId(newItemId);
        relevanceEntity.setCreateName(UserUtils.getCurentUser().getUserId().toString());
        erpOrderAllotRelevanceService.save(relevanceEntity);
    }


    /**
     * 商品分配：报价商品（请求API生成订单信息）
     */
    public OrderResult<AllotOrderResultDto> requestItemAllotQuoteApi(String orderNo, int itemId, boolean self, int producer, boolean quoteType) {
        logger.info("=================goods allot quote api start==================");
        // 地址信息
        SellerInfoEntity sellerInfoEntity = sellerInfoService.getById(UserUtils.getCurentUser().getSellerId());
        AddressResultDto addressResultDto = new AddressResultDto();
        addressResultDto.setAddressId(sellerInfoEntity.getSellerId());
        addressResultDto.setName(sellerInfoEntity.getSellerName());
        addressResultDto.setArea(sellerInfoEntity.getArea());
        addressResultDto.setAreaId(Integer.valueOf(sellerInfoEntity.getAreaId()));
        addressResultDto.setAddr(sellerInfoEntity.getAddr());
        addressResultDto.setMobile(sellerInfoEntity.getSellerMobile());
        addressResultDto.setPickUp(true);
        // 商品分配信息
        List<AllotProductParamDto> AllotProductParamDtoList = new ArrayList<>();
        AllotProductParamDto allotProductParamDto = new AllotProductParamDto();
        // 小B参考工厂ID
        allotProductParamDto.setReferToSellerId(Long.valueOf(producer));
        allotProductParamDto.setOrderItemId(itemId);
        allotProductParamDto.setSellerId(Long.valueOf(producer));
        AllotProductParamDtoList.add(allotProductParamDto);
        // 订单信息
        ErpAllotFactoryOrderParamDto erpAllotFactoryOrderParamDto = ErpAllotFactoryOrderParamDto.builder()
                .allotOrderId(orderNo)
                .userId(UserUtils.getCurentUser().getMallUserId())
                .sellerId(UserUtils.getCurentUser().getSellerId())
                .self(self)
                .goodsSplitType(quoteType == true ? com.service.common.constant.GoodsSplitType.quoteGoods : com.service.common.constant.GoodsSplitType.standardGoods)
                .address(addressResultDto)
                .quoteParam(AllotProductParamDtoList)
                .build();

        logger.info("=================goods allot quote api param:" + erpAllotFactoryOrderParamDto.toString());
        OrderResult<AllotOrderResultDto> allotOrderResultDtoOrderResult = this.orderAllotApi(erpAllotFactoryOrderParamDto);
        logger.info("=================goods allot quote api result:" + allotOrderResultDtoOrderResult.toString());
        logger.info("=================goods allot quote api end==================");
        return allotOrderResultDtoOrderResult;
    }


    /**
     * 商品工序列表
     *
     * @param erpItemId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R orderCraftsInfo(Integer erpItemId) {
        //先根据erpItemId查询是否有关联的orderItemId
        ErpOrderItemEntity erpOrderItemEntity = erpOrderItemService.getById(erpItemId);
        String orderNo=erpOrderItemEntity.getOrderNo();
      /*  //判断是否已经
        int count = erpOrderProductionService.count(new QueryWrapper<>(new ErpOrderProductionEntity())
                .eq("order_no", orderNo)
                .eq("erp_item_id", erpItemId)
                .eq("del", DeleteEnum.NOT_DELETE.toInt())
                .notIn("production_status", OrderProductionStatusEnum.CANCLE.toInt())
        );
        if (count > 0) {
            return R.error("商品已存在分配信息！");
        }*/

        OrderItemEntity orderItemEntity = new OrderItemEntity();
        if (erpOrderItemEntity.getOriginalItemId() == null) {
            orderItemEntity = ErpOrderUtils.erpToZiyunOrderItem(erpOrderItemEntity, erpOrderItemEntity.getOrderNo());
            orderItemService.save(orderItemEntity);
            erpOrderItemEntity.setOriginalItemId(orderItemEntity.getItemId());
            erpOrderItemService.updateById(erpOrderItemEntity);
        }
        Integer itemId = erpOrderItemEntity.getOriginalItemId();
        OrderItemEntity orderItem = orderItemService.getById(itemId);
        Long goodsId = orderItem.getGoodsId();
        String attributeOption = orderItem.getAttributeOption();
        if (com.utility.StringUtils.isBlank(attributeOption)) {
            return R.error("缺少工序分配参数");
        }

        // 查询分配工序列表
        List<OrderCraftQuoteDto> allotedList = erpOrderProductionService.selectAllotedCraftsList(itemId);
        // 查询分配服务工序信息、自做工序信息
       /* ErpOrderItemEntity erpOrderItem = erpOrderItemService.selectByItemId(itemId);
        Integer eoItemId = erpOrderItem.getEoItemId();*/
        List<OrderCraftServerVo> serverList = erpOrderProductionService.selectAllotedServerCraftsList(erpItemId);
        // 查询自做外协信息（中浩紫云）
        List<ErpSupplierOfflineEntity> erpSupplierOfflineList = erpSupplierOfflineService.getListBySupplierName(ErpOrderStateContext.ZIYUN_SUPP_NAME);
        ErpSupplierOfflineEntity erpSupplierOffline = erpSupplierOfflineList.get(0);

        Map<String, Map<AttributeValueType, Integer>> map = JSONObject.parseObject(attributeOption, Map.class);
        int size = map.size();
        List<QuoteAllotCraftsVo> craftsVoList = new ArrayList<>();
        Map<String, Object> queryMap = new HashMap<>();
        boolean mainPartSize = false;
        for (Map.Entry<String, Map<AttributeValueType, Integer>> entry : map.entrySet()) {
            /**
             * 部件名称：size等于1为单部件，查询分类表；大于1 多部件 查询部件表；
             * 主部件工艺不参与分配，size（印刷）参与其他子部件分配
             */
            String key = entry.getKey();
            Map<AttributeValueType, Integer> value = entry.getValue();
            Set<AttributeValueType> attributeValueTypes = value.keySet();
            boolean sizeType = attributeValueTypes.contains(AttributeValueType.size.toString());
            boolean materialType = attributeValueTypes.contains(AttributeValueType.material.toString());
            String partName = null;
            if (size > 1) {
                QuotePartsEntity quoteParts = quotePartsService.getById(key);
                // 主部件不参与工序分配
                if (quoteParts.getIsMainPart()) {
                    mainPartSize = sizeType;
                    continue;
                }
                partName = quoteParts.getPartsName();
            } else {
                GoodsCategoryEntity goodsCategory = goodsCategoryService.getById(key);
                partName = goodsCategory.getCategoryName();
            }
            // 材料工艺
            if (materialType) {
                QuoteAllotCraftsVo quoteAllotCraftsVo = new QuoteAllotCraftsVo();
                quoteAllotCraftsVo.setPartId(Integer.valueOf(key));
                quoteAllotCraftsVo.setPartsName(partName);
                quoteAllotCraftsVo.setAttributeName("纸张");
                quoteAllotCraftsVo.setCraftValueType(AttributeValueType.material.toString());
                quoteAllotCraftsVo.setSplitProcessType(SplitProcessType.material.toString());
                craftsVoList.add(quoteAllotCraftsVo);
            }
            // 印刷工艺
            if (mainPartSize || sizeType) {
                QuoteAllotCraftsVo quoteAllotCraftsVo = new QuoteAllotCraftsVo();
                quoteAllotCraftsVo.setPartId(Integer.valueOf(key));
                quoteAllotCraftsVo.setPartsName(partName);
                quoteAllotCraftsVo.setAttributeName("印刷");
                quoteAllotCraftsVo.setCraftValueType(AttributeValueType.size.toString());
                quoteAllotCraftsVo.setSplitProcessType(SplitProcessType.print.toString());
                craftsVoList.add(quoteAllotCraftsVo);
            }

            Collection<Integer> values = value.values();
            List ids = new ArrayList(values);
            queryMap.put("mapSize", size);
            queryMap.put("goodsId", goodsId);
            queryMap.put("optionIds", ids);
            List<QuoteAllotCraftsVo> list = quoteProductBaseInfoService.getCraftsAllotInfo(queryMap);
            if (size > 1) {
                // 去除主部件工艺
                List<QuoteAllotCraftsVo> collect = list.stream().filter(item -> !item.getIsMainPart()).collect(Collectors.toList());
                craftsVoList.addAll(collect);
            } else {
                craftsVoList.addAll(list);
            }

            // 回显已分配工序信息
            for (QuoteAllotCraftsVo craftsVo : craftsVoList) {
                List<OrderCraftQuoteDto> allotedListCollect = allotedList.stream().filter(item -> item.getPartId().intValue() == craftsVo.getPartId() && item.getCraftValueType().equals(craftsVo.getCraftValueType()))
                        .collect(Collectors.toList());
                if (allotedListCollect.size() > 0) {
                    OrderCraftQuoteDto orderCraftQuoteDto = allotedListCollect.get(0);
                    craftsVo.setFactoryName(orderCraftQuoteDto.getFactoryName());
                    craftsVo.setAddress(orderCraftQuoteDto.getAddress());
                    craftsVo.setContacts(orderCraftQuoteDto.getContacts());
                    craftsVo.setContactWay(orderCraftQuoteDto.getContactWay());
                    craftsVo.setTotalPrice(orderCraftQuoteDto.getTotalPrice());
                    craftsVo.setRemark(orderCraftQuoteDto.getRemark());
                    craftsVo.setAlloted(true);
                    craftsVo.setIsOwn(false);
                } else {
                    List<OrderCraftServerVo> serverListCollect = serverList.stream().filter(item -> item.getPartId().intValue() == craftsVo.getPartId() && item.getAttributeTypeValue().equals(craftsVo.getCraftValueType()))
                            .collect(Collectors.toList());
                    if (serverListCollect.size() > 0) {
                        OrderCraftServerVo orderCraftServerVo = serverListCollect.get(0);
                        craftsVo.setFactoryName(orderCraftServerVo.getSupplierName());
                        craftsVo.setAddress(orderCraftServerVo.getContactAddr());
                        craftsVo.setContacts(orderCraftServerVo.getContactsName());
                        craftsVo.setContactWay(orderCraftServerVo.getContactTel());
                        craftsVo.setTotalPrice(orderCraftServerVo.getTotalPrice());
                        craftsVo.setRemark(orderCraftServerVo.getRemark());
                        craftsVo.setAlloted(true);
                        craftsVo.setIsOwn(true);
                        serverList.removeAll(serverListCollect);
                    }
                }
            }
        }

        return R.ok().put("craftsList", craftsVoList)
                .put("serverCraftsList", serverList)
                .put("erpSupplierOffline", erpSupplierOffline)
                .put("itemId", itemId);
    }

    /**
     * 工艺找工厂
     *
     * @param orderCraftQuoteDto
     * @return
     */
    @Override
    public R orderCraftAllotFindFactory(OrderCraftQuoteDto orderCraftQuoteDto) {
        logger.info("================= craft item find factory api start==================");
        Integer orderItemId = orderCraftQuoteDto.getOrderItemId();
        String splitProcessType = orderCraftQuoteDto.getSplitProcessType();
        String craftValueType = orderCraftQuoteDto.getCraftValueType();
        Integer partId = orderCraftQuoteDto.getPartId();
        OrderItemEntity orderItem = orderItemService.getById(orderItemId);
        Long orderId = orderItem.getOrderId();

        MultyErpOrderParam multyErpOrderParam = new MultyErpOrderParam();
        multyErpOrderParam.setAllotOrderId(orderId.toString());
        multyErpOrderParam.setGoodsSplitType(com.service.common.constant.GoodsSplitType.quoteGoodsSplit);
        multyErpOrderParam.setOrderItemId(orderItemId);
        multyErpOrderParam.setPartId(partId);
        multyErpOrderParam.setSplitProcessType(com.service.common.constant.SplitProcessType.valueOf(splitProcessType));
        multyErpOrderParam.setCraftValueType(com.service.model.quote.constant.AttributeValueType.valueOf(craftValueType));
        SellerInfoEntity sellerInfoEntity = sellerInfoService.getById(UserUtils.getCurentUser().getSellerId());
        //判断是自营门店还是第三方供应商
        if(sellerInfoEntity.getSelf()==1){
            multyErpOrderParam.setOrderSplitType(OrderSplitType.self_shop);
        }else{
            multyErpOrderParam.setOrderSplitType(OrderSplitType.third_supplier);
        }
        logger.info("================= craft find factory api param：" + JsonUtils.object2String(multyErpOrderParam));
        GoodsResult<?> goodsForOrderErp = goodsAlloteService.getGoodsForOrderErp(multyErpOrderParam);
        int code = goodsForOrderErp.getCode();
        if (code != 1) {
            return R.error(goodsForOrderErp.getMessage());
        }
        LinkedHashMap result = (LinkedHashMap) goodsForOrderErp.getData();
        // 符合报价产品的条件的工厂详情
        List<FactoryQuoteInfo> factoryQuoteInfos = (List<FactoryQuoteInfo>) result.get("factoryQuoteInfos");
        // 报价产品的相关信息 todo 解析有问题
//        QuoteProductResultVO productVO = (QuoteProductResultVO) result.get("productVO");
        // 报价产品参数
        String quoteProductDetail = (String) result.get("quoteProductDetail");
        return R.ok().put("factoryQuoteInfos", factoryQuoteInfos);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R allotOrderCrafts(OrderCraftsDto orderCraftsDto) {
        List<OrderCraftQuoteDto> orderCraftQuoteList = orderCraftsDto.getOrderCraftQuoteList();
        List<OrderCraftServerDto> orderCraftServerList = orderCraftsDto.getOrderCraftServerList();
        if (orderCraftQuoteList.size() == 0 && orderCraftServerList.size() == 0) {
            return R.error("未提交分配工序信息");
        }
        String orderNo = orderCraftsDto.getOrderNo();
        Integer erpItemId = orderCraftsDto.getErpItemId();
        Long sellerId = UserUtils.getCurentUser().getSellerId();
        ErpOrderEntity erpOrderEntity = this.getById(orderNo);
        String allotType = AllotTypeEnum.PROCEDURE.toCode();

        ErpOrderItemEntity erpOrderItem = erpOrderItemService.getById(erpItemId);
        ErpOrderProductionEntity erpOrderProductionEntity = erpOrderProductionService.getOne(new QueryWrapper<ErpOrderProductionEntity>()
                .eq("order_no", orderNo).eq("del", 0)
                .notIn("allot_type",AllotTypeEnum.ORDER.toCode()).notIn("production_status",4));
        if(erpOrderProductionEntity!=null){
            if(!erpOrderProductionEntity.getAllotType().equals(ProducerTypeEnum.ZIYUN_SUPPLIER)){
                return  R.error("已分配商品无需再次分配!");
            }
        }

        if (erpOrderItem.getStatus().intValue() != OrderItemStatusEnum.UN_ALLOTED.toInt()
                && erpOrderItem.getStatus().intValue() != OrderItemStatusEnum.IN_PRODUCTION.toInt()) {
            return R.error("商品状态异常！");
        }

        logger.info("=================craft allot quote api start==================");

        // 地址信息
        SellerInfoEntity sellerInfoEntity = sellerInfoService.getById(sellerId);
        AddressResultDto addressResultDto = new AddressResultDto();
        addressResultDto.setAddressId(sellerInfoEntity.getSellerId());
        addressResultDto.setName(sellerInfoEntity.getSellerName());
        addressResultDto.setArea(sellerInfoEntity.getArea());
        addressResultDto.setAreaId(Integer.valueOf(sellerInfoEntity.getAreaId()));
        addressResultDto.setAddr(sellerInfoEntity.getAddr());
        addressResultDto.setMobile(sellerInfoEntity.getSellerMobile());
        addressResultDto.setPickUp(true);
        // 商品分配信息
        List<AllotProductParamDto> AllotProductParamDtoList = new ArrayList<>();
        for (OrderCraftQuoteDto orderCraftQuoteDto : orderCraftQuoteList) {
            AllotProductParamDto allotProductParamDto = new AllotProductParamDto();
            allotProductParamDto.setOrderItemId(orderCraftQuoteDto.getOrderItemId());
            allotProductParamDto.setPartId(orderCraftQuoteDto.getPartId());
            allotProductParamDto.setSplitProcessType(SplitProcessType.valueOf(orderCraftQuoteDto.getSplitProcessType()));
            allotProductParamDto.setCraftValueType(com.service.model.quote.constant.AttributeValueType.valueOf(orderCraftQuoteDto.getCraftValueType()));
            allotProductParamDto.setSellerId(Long.valueOf(orderCraftQuoteDto.getSellerId()));
            allotProductParamDto.setProductId(Long.valueOf(orderCraftQuoteDto.getProductId()));
            if (sellerInfoEntity.getSelf().intValue() == 1) {
                allotProductParamDto.setReferToSellerId(ZIYUN_FACTORY_ID);
            } else {
                allotProductParamDto.setReferToSellerId(Long.valueOf(sellerId));
            }
            AllotProductParamDtoList.add(allotProductParamDto);
        }
        // 分配信息
        // 全部选的自营供应商分配为 true， 其他为 false
        boolean self = false;
        long count = orderCraftQuoteList.stream().filter(item -> !item.getSelf()).count();
        if (count == 0) {
            self = true;
        }
        ErpAllotFactoryOrderParamDto erpAllotFactoryOrderParamDto = ErpAllotFactoryOrderParamDto.builder()
                .allotOrderId(orderNo)
                .userId(UserUtils.getCurentUser().getMallUserId())
                .sellerId(sellerId)
                .self(self)
                .goodsSplitType(GoodsSplitType.quoteGoodsSplit)
                .address(addressResultDto)
                .quoteParam(AllotProductParamDtoList)
                .build();
        logger.info("=================order allot quote api param:" + erpAllotFactoryOrderParamDto.toString());
        OrderResult<AllotOrderResultDto> allotOrderResultDtoOrderResult = mallErpOrderService.allotFactoryOrder(erpAllotFactoryOrderParamDto);
        if (allotOrderResultDtoOrderResult == null) {
            return R.error("调用接口服务失败！");
        }
        int code = allotOrderResultDtoOrderResult.getCode();
        if (code != 1) {
            return R.error(allotOrderResultDtoOrderResult.getMessage());
        }
        AllotOrderResultDto allotOrderResultDto = allotOrderResultDtoOrderResult.getData();
        List<OldItemNew> itemList = allotOrderResultDto.getItemList();
        for (OldItemNew re : itemList) {
            String newOrderId = re.getNewOrderId();
            int oldItemId = re.getOldItemId();
            int newItemId = re.getNewItemId();
            int partId = re.getPartId();
            String craftValueType = re.getCraftValueType().toString();
            String splitProcessType = re.getSplitProcessType().toString();
            List<OrderCraftQuoteDto> collect = orderCraftQuoteList.stream()
                    .filter(item -> item.getPartId().intValue() == partId && item.getCraftValueType().equals(craftValueType) && item.getSplitProcessType().equals(splitProcessType))
                    .collect(Collectors.toList());
            OrderCraftQuoteDto orderCraftQuoteDto = collect.get(0);

            // 生成生产单
            ErpOrderProductionEntity erpOrderProduction = new ErpOrderProductionEntity();
            erpOrderProduction.setOrderNo(orderNo);
            erpOrderProduction.setPartId(partId);
            erpOrderProduction.setAttributeTypeValue(craftValueType);
            erpOrderProduction.setAttributeName(EnumUtil.getEnumByCode(QuoteAttributeValueEnum.class, craftValueType).toDescribe());
            erpOrderProduction.setAllotType("procedure");
            erpOrderProduction.setOnlineCash(1);
            erpOrderProduction.setErpItemId(erpOrderItem.getEoItemId().toString());
            erpOrderProduction.setOrderItemId(erpOrderItem.getOriginalItemId().toString());
            erpOrderProduction.setAddon(erpOrderItem.getAddon());
            erpOrderProduction.setUnit(erpOrderItem.getUnit());
            erpOrderProduction.setNums(erpOrderItem.getNums());
            erpOrderProduction.setProducer(orderCraftQuoteDto.getSellerId());
            erpOrderProduction.setProducerType(ProducerTypeEnum.QUOTE_FACTORY.toInt());
            erpOrderProduction.setCost(orderCraftQuoteDto.getTotalPrice());
            if(orderCraftQuoteDto.getTotalPrice().compareTo(new BigDecimal(0))>0){
                erpOrderProduction.setCostStatus(true);
            }else{
                erpOrderProduction.setCostStatus(false);
            }
            erpOrderProduction.setProductionStatus(OrderProductionStatusEnum.FINISH.toInt());
            erpOrderProduction.setCreateName(UserUtils.getCurentUser().getUserId().toString());
            erpOrderProduction.setProductionOrder(newOrderId);
            erpOrderProduction.setCsRemark(orderCraftQuoteDto.getRemark());
            erpOrderProductionService.save(erpOrderProduction);
            // 保存分配关系
            ErpOrderAllotRelevanceEntity relevanceEntity = new ErpOrderAllotRelevanceEntity();
            relevanceEntity.setOriginalOrderNo(orderNo);
            relevanceEntity.setOrderAllotNo(newOrderId);
            relevanceEntity.setProductionId(erpOrderProduction.getProductionId());
            relevanceEntity.setOriginalItemId(oldItemId);
            relevanceEntity.setItemAllotId(newItemId);
            relevanceEntity.setCreateName(UserUtils.getCurentUser().getUserId().toString());
            erpOrderAllotRelevanceService.save(relevanceEntity);
        }

        // 是否添加服务工序
        if (orderCraftServerList != null && orderCraftServerList.size() > 0) {
            List<ErpOrderProductionEntity> productionList = new ArrayList<>(orderCraftServerList.size());
            for (OrderCraftServerDto orderCraftServerDto : orderCraftServerList) {
                ErpOrderProductionEntity erpOrderProduction = new ErpOrderProductionEntity();
                erpOrderProduction.setAttributeTypeValue(orderCraftServerDto.getCraftValueType());
                // 部件ID 不为空，为自做工序，否则为服务工序
                if (orderCraftServerDto.getPartId() != null) {
                    erpOrderProduction.setAttributeName(EnumUtil.getEnumByCode(QuoteAttributeValueEnum.class, orderCraftServerDto.getCraftValueType()).toDescribe());
                } else {
                    erpOrderProduction.setAttributeName(EnumUtil.getEnumByCode(ServerCraftEnum.class, orderCraftServerDto.getCraftValueType()).toDescribe());
                }
                // 是否自做
                if (orderCraftServerDto.getIsOwn()) {
                    erpOrderProduction.setIsOwn(1);
                }
                erpOrderProduction.setPartId(orderCraftServerDto.getPartId());
                erpOrderProduction.setProducer(orderCraftServerDto.getSupplierId());
                erpOrderProduction.setCost(orderCraftServerDto.getTotalPrice());
                if(orderCraftServerDto.getTotalPrice().compareTo(new BigDecimal(0))>0){
                    erpOrderProduction.setCostStatus(true);
                }else{
                    erpOrderProduction.setCostStatus(false);
                }
                erpOrderProduction.setCsRemark(orderCraftServerDto.getRemark());
                erpOrderProduction.setOrderNo(orderNo);
                erpOrderProduction.setAllotType(allotType);
                erpOrderProduction.setErpItemId(erpItemId.toString());
                erpOrderProduction.setOrderItemId(erpOrderItem.getOriginalItemId().toString());
                erpOrderProduction.setAddon(erpOrderItem.getAddon());
                erpOrderProduction.setUnit(erpOrderItem.getUnit());
                erpOrderProduction.setNums(erpOrderItem.getNums());
                erpOrderProduction.setProductionStatus(OrderProductionStatusEnum.PRODUCING.toInt());
                erpOrderProduction.setCreateName(UserUtils.getCurentUser().getUserId().toString());
                erpOrderProduction.setProducerType(ProducerTypeEnum.ZIYUN_SUPPLIER.toInt());
                erpOrderProduction.setOnlineCash(0);
                productionList.add(erpOrderProduction);
            }
            erpOrderProductionService.saveBatch(productionList);
        }

        // 订单商品状态 待分配 =》 生产中
        Map<String, Object> updateMap = new HashMap<>();
        if (erpOrderItem.getStatus().intValue() == OrderItemStatusEnum.IN_PRODUCTION.toInt()) {
            updateMap.put("status", OrderItemStatusEnum.IN_PRODUCTION.toInt());
            erpOrderItemService.updateByMap(updateMap, Integer.valueOf(erpItemId));
        }

        // 订单状态 待分配 =》 生产中
        updateMap.clear();
        //  updateMap.put("csId", csId);
        // updateMap.put("pmcId", pmcId);
        updateMap.put("allotName", UserUtils.getCurentUser().getUserId());
        updateMap.put("allotTime", DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        updateMap.put("productionStatus", ProductionStatusEnum.IN_PRODUCTION.toInt());
        this.updateByMap(updateMap, orderNo);
        return R.ok();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R deleteAllotItem(Integer productionId) {
        ErpOrderProductionEntity erpOrderProduction = erpOrderProductionService.getById(productionId);
        String allotType = erpOrderProduction.getAllotType();
        Integer producerType = erpOrderProduction.getProducerType();
        String orderNo = erpOrderProduction.getOrderNo();
        String erpItemId = erpOrderProduction.getErpItemId();
        Integer producer = erpOrderProduction.getProducer();
        Integer productionStatus = erpOrderProduction.getProductionStatus();
        String productionOrder = erpOrderProduction.getProductionOrder();
        //先判断是添加的外协商还是一键分配的
        if(producerType==(ProducerTypeEnum.ZIYUN_SUPPLIER.toInt())){
            //如果是外协商,判断当前财务审核状态
            Integer financeStatus = erpOrderProduction.getFinanceStatus();
            if(financeStatus==FinanceStatusEnum.UN_AUDITED.toInt()){
                //为待审核，则允许删除生产单,4为取消
                erpOrderProduction.setProductionStatus(ProductionStatus.PRODUCTION_STATUS_4.toInt());
                erpOrderProduction.setDel(DeleteEnum.DELETE.toInt());
                erpOrderProduction.setUpdateName(UserUtils.getCurentUser().getUsername());
                erpOrderProduction.setUpdateTime(new Date());
                erpOrderProductionService.updateById(erpOrderProduction);
                //添加操作日志
                ErpOrderLogEntity erpOrderLogEntity = new ErpOrderLogEntity();
                erpOrderLogEntity.setLogText("删除分配信息，分配productionId:"+productionId);
                erpOrderLogEntity.setOrderNo(orderNo);
                erpOrderLogEntity.setCreateTime(new Date());
                erpOrderLogEntity.setCreateName(UserUtils.getCurentUser().getUsername());
                erpOrderLogService.save(erpOrderLogEntity);
                //再判断这个商品是否还有分配信息，无则将此商品状态改为待分配
                int count = erpOrderProductionService.count(new QueryWrapper<ErpOrderProductionEntity>().eq("erp_item_id", erpItemId)
                        .eq("del", DeleteEnum.NOT_DELETE.toInt()).notIn("production_status", ProductionStatus.PRODUCTION_STATUS_4.toInt()));
                if(count<=0){
                    ErpOrderItemEntity erpOrderItemEntity = erpOrderItemService.getById(erpItemId);
                    //商品状态修改为待审核
                    erpOrderItemEntity.setStatus(OrderItemStatusEnum.UN_ALLOTED.toInt());
                    erpOrderItemService.updateById(erpOrderItemEntity);
                    return R.ok();
                }

            }else{
                return  R.error("分配订单已审核或者付款，请联系管理员!");
            }
        }else{
            OrderInfoEntity orderInfo = orderInfoService.getById(productionOrder);
            String payStatus = orderInfo.getPayStatus();
            if (StringUtils.equals(payStatus, PayStatusEnum.ALREADY_PAY_1.toCode())) {
                return R.error("分配订单已支付，无法删除");
            }
            Map<String, Object> updateMap = new HashMap<>();
            // 取消分配信息
            erpOrderAllotRelevanceService.cancleAllotInfo(productionId);
            // 作废分配订单
            if (productionOrder != null) {
                updateMap.put("status", OrderInfoStatusEnum.DEAD.toCode());
                orderInfoService.updateByMap(updateMap, productionOrder);
            }
            // 取消生产单
            updateMap.put("productionStatus", OrderProductionStatusEnum.CANCLE.toInt());
            erpOrderProductionService.updateByMap(updateMap, productionId);

            if (StringUtils.equals(allotType, AllotTypeEnum.GOODS.toCode())) { // 商品分配
                // 商品状态 生产中 =》 待分配
                updateMap.put("status", OrderItemStatusEnum.UN_ALLOTED.toInt());
                erpOrderItemService.updateByMap(updateMap, Integer.valueOf(erpItemId));
                // 订单状态  所有商品是否取消分配（生产中 =》 待分配）
                List<ErpOrderItemEntity> erpOrderItemList = erpOrderItemService.selectListByErpOrder(orderNo);
                long count = erpOrderItemList.stream()
                        .filter(item -> item.getStatus().intValue() != OrderItemStatusEnum.UN_ALLOTED.toInt())
                        .count();
                if (count == 0) {
                    this.cancelOrderAllotInfo(orderNo);
                }
            } else { // 工序分配
                // 商品状态  所有生产单是否取消分配（生产中 =》 待分配）
                List<Integer> notInStatus = new ArrayList<>();
                notInStatus.add(OrderProductionStatusEnum.CANCLE.toInt());
                List<ErpOrderProductionEntity> productionList = erpOrderProductionService.list(new QueryWrapper<>(new ErpOrderProductionEntity())
                        .eq("erp_item_id", erpItemId)
                        .notIn("production_status", notInStatus)
                        .eq("del", DeleteEnum.NOT_DELETE.toInt())
                );
                if (productionList.size() == 0) {
                    updateMap.put("status", OrderItemStatusEnum.UN_ALLOTED.toInt());
                    erpOrderItemService.updateByMap(updateMap, Integer.valueOf(erpItemId));
                }
            }
        }
        logger.info("=================WaitProducingState cancleAllot end==================");
        return R.ok();
    }

    @Override
    public boolean cancelOrderAllotInfo(String orderNo) {
        int update = this.baseMapper.cancelOrderAllotInfo(orderNo);
        if (update == 0) {
            return false;
        }
        return true;
    }

    @Override
    public OrderResult<AllotOrderResultDto> orderAllotApi(ErpAllotFactoryOrderParamDto erpAllotFactoryOrderParamDto) {
        OrderResult<AllotOrderResultDto> allotOrderResultDtoOrderResult = mallErpOrderService.allotFactoryOrder(erpAllotFactoryOrderParamDto);
        return allotOrderResultDtoOrderResult;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R suppSave(OrderSupplierDto orderSupplierDto, Long userId) {
        OrderInfoEntity orderInfoEntity = orderInfoService.getById(orderSupplierDto.getOrderId());
        Integer eoItemId= orderSupplierDto.getEoItemId();
        //根据eoItemId查询出ogriginalItemId
        ErpOrderItemEntity orderItemEntity = erpOrderItemService.getById(eoItemId);
        //查询生产成本已经录入完成,则不允许添加外协
        ErpOrderEntity erpOrderEntity = this.getById(orderItemEntity.getOrderNo());
        if(erpOrderEntity.getCommissionStatus()!=CommissionStatusEnum.NOTENTERED.toInt()){
            return R.error("生产成本录入完成订单不允许添加外协!");
        }
        Integer originalItemId = orderItemEntity.getOriginalItemId();
        ErpOrderProductionEntity erpOrderProduction = new ErpOrderProductionEntity();
        erpOrderProduction.setOrderNo(orderSupplierDto.getOrderId());
        erpOrderProduction.setErpItemId(orderSupplierDto.getEoItemId().toString());
        erpOrderProduction.setOrderItemId(originalItemId.toString());
        erpOrderProduction.setAttributeName(orderSupplierDto.getAttributeName());
        erpOrderProduction.setCost(orderSupplierDto.getCost());
        if(orderSupplierDto.getCost().compareTo(new BigDecimal(0))>0){
            erpOrderProduction.setCostStatus(true);
        }else{
            erpOrderProduction.setCostStatus(false);
        }
        erpOrderProduction.setProducer(orderSupplierDto.getSupplierId());
        erpOrderProduction.setCsRemark(orderSupplierDto.getCsRemark());
        erpOrderProduction.setProductionStatus(OrderProductionStatusEnum.FINISH.toInt());
        erpOrderProduction.setProducerType(ProducerTypeEnum.ZIYUN_SUPPLIER.toInt());
        //外协从erp_supplier_offline表中查询
        ErpSupplierOfflineEntity erpSupplierOfflineEntity = erpSupplierOfflineService.selectByProduId(orderSupplierDto.getSupplierId());
        if(erpSupplierOfflineEntity!=null){
            erpOrderProduction.setProducerName(erpSupplierOfflineEntity.getSupplierName());
        }
        erpOrderProduction.setCreateName(userId.toString());
        erpOrderProduction.setAllotType(AllotTypeEnum.GOODS.toCode());
        erpOrderProductionService.save(erpOrderProduction);
        //判断此商品的分配状态
        ErpOrderItemEntity erpOrderItemEntity = erpOrderItemService.getById(orderSupplierDto.getEoItemId().toString());
        if(erpOrderItemEntity.getStatus()==OrderItemStatusEnum.UN_ALLOTED.toInt()){
            //如果为待分配，则需要将商品状态改为生产中
            Map<String, Object> updateMap=new HashMap<>();
            updateMap.put("status",OrderItemStatusEnum.IN_PRODUCTION.toInt());
            erpOrderItemService.updateByMap(updateMap,orderSupplierDto.getEoItemId());
        }
        erpOrderLogService.insertOrderItemLog(orderSupplierDto.getOrderId(), Long.valueOf(originalItemId), "添加外协商");

        return R.ok();
    }

    //添加数据到orderInfo和order_item中
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean copyQuoteToOrderInfo(Integer eoItemId) {
        boolean flag = true;
        //先查询出erp_order_item
        ErpOrderItemEntity erpOrderItemEntity = erpOrderItemService.getById(eoItemId);
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        //获取original_item_id
        Integer originalItemId = erpOrderItemEntity.getOriginalItemId();
        if (originalItemId == null) {
            orderItemEntity = ErpOrderUtils.erpToZiyunOrderItem(erpOrderItemEntity, erpOrderItemEntity.getOrderNo());
            orderItemService.save(orderItemEntity);
            erpOrderItemEntity.setOriginalItemId(orderItemEntity.getItemId());
            flag = erpOrderItemService.updateById(erpOrderItemEntity);
        }
        //判断订单是否存在于order_info表
        OrderInfoEntity orderInfoEntity = orderInfoService.getById(erpOrderItemEntity.getOrderNo());
        if (orderInfoEntity == null) {
            ErpOrderEntity erpOrderEntity = this.getById(erpOrderItemEntity.getOrderNo());
            //查询订单
            orderInfoEntity = ErpOrderUtils.erpToZiyunOrder(erpOrderEntity);
            flag = orderInfoService.save(orderInfoEntity);
        }
        return flag;
    }

    /**
     * 调价
     *
     * @param erpOrder
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R updateDiscount(ErpOrderEntity erpOrder) {
        //根据订单号查询订单信息
        ErpOrderEntity erpOrderEntity = this.getById(erpOrder.getOrderNo());
        if(!erpOrderEntity.getProductionStatus().equals(ProductionStatusEnum.IN_PRODUCTION.toInt())&&(!erpOrderEntity.getProductionStatus().equals(ProductionStatusEnum.NEW_ORDER.toInt()))){
            return  R.error("只允许新开单或生产中订单进行调价!");
        }
        BigDecimal discount = erpOrder.getDiscount();
        if(discount==null){
            discount=new BigDecimal(0);
        }
        erpOrderEntity.setDiscount(discount);
        BigDecimal payableAmount = erpOrder.getPayableAmount().add(discount);
        erpOrderEntity.setPayableAmount(payableAmount);
        this.updateById(erpOrderEntity);
        //判断order_info表中是否也存在对应信息，如存在，则需同步更改
        OrderInfoEntity orderInfoEntity = orderInfoService.getOne(new QueryWrapper<OrderInfoEntity>().eq("order_id", erpOrder.getOrderNo()).eq("status", OrderInfoStatusEnum.ACTIVE.toCode()));
        if(orderInfoEntity!=null) {
            orderInfoEntity.setDiscount(erpOrderEntity.getDiscount());
            orderInfoEntity.setPayableAmount(erpOrderEntity.getPayableAmount());
            orderInfoService.updateById(orderInfoEntity);
        }
        //添加操作日志
        ErpOrderLogEntity erpOrderLogEntity = new ErpOrderLogEntity();
        erpOrderLogEntity.setLogText("订单调价,调价金额为:"+discount);
        erpOrderLogEntity.setOrderNo(erpOrderEntity.getOrderNo());
        erpOrderLogEntity.setCreateTime(new Date());
        erpOrderLogEntity.setCreateName(UserUtils.getCurentUser().getUsername());
        erpOrderLogService.save(erpOrderLogEntity);
        return R.ok();
    }

    /**
     * 删除商品
     *
     * @param
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R deleteGoods(Integer eoItemId) {
        //先删除商品,再重新计算价格
        ErpOrderItemEntity erpOrderItemEntity = erpOrderItemService.getById(eoItemId);
        erpOrderItemEntity.setItemDel(1);
        //删除当前这件商品
        erpOrderItemService.updateById(erpOrderItemEntity);
        //订单号
        String orderNo = erpOrderItemEntity.getOrderNo();
        //获取订单
        ErpOrderEntity erpOrderEntity= this.getById(orderNo);
        Integer memberId = erpOrderEntity.getMemberId();
        //查询订单,得到会员信息
        StoreMemberEntity storeMemberEntity=storeMemberService.getOne(new QueryWrapper<StoreMemberEntity>().eq("member_id",memberId)
                .eq("seller_id",UserUtils.getCurentUser().getSellerId()));
        //根据订单号得到所有其他所有订单明细
        List<ErpOrderItemEntity> erpOrderItemEntityList = erpOrderItemService.list(new QueryWrapper<ErpOrderItemEntity>().eq("order_no", orderNo).eq("item_del", 0));
        //定义一个变量接收商品总值
        BigDecimal totalAmount=new BigDecimal(0);
        //定义一个变量接收订单应付金额
        BigDecimal payableAmount=new BigDecimal(0);
        //先重新计算出所有商品的总额
        for (int i=0;i<erpOrderItemEntityList.size();i++){
           ErpOrderItemEntity erpOrderItem=erpOrderItemEntityList.get(i);
            BigDecimal amount = erpOrderItem.getAmount();
            totalAmount=totalAmount.add(amount);
            //如果为报价商品
            if(erpOrderItem.getAddcartBuyType().equals(AddcartBuyTypeEnum.PRINT.toCode())||erpOrderItem.getAddcartBuyType().equals(AddcartBuyTypeEnum.FAST.toCode())){
                payableAmount=payableAmount.add(getNotStandardTotalAmount(erpOrderItem,storeMemberEntity));
            }else{
                //按标品计算
                payableAmount=payableAmount.add(getTotalAmount(erpOrderItem,storeMemberEntity));
            }
        }
        //优惠金额，为正数
        BigDecimal pmtGoods=totalAmount.subtract(payableAmount);
        //修改优惠金额
        erpOrderEntity.setPmtGoods(pmtGoods);
        //应付金额=调价+应付金额
        BigDecimal discount = erpOrderEntity.getDiscount();
        if(discount!=null){
            payableAmount=erpOrderEntity.getDiscount().add(payableAmount);
        }
        erpOrderEntity.setPayableAmount(payableAmount.setScale(2,BigDecimal.ROUND_DOWN));
        erpOrderEntity.setTotalAmount(totalAmount.setScale(2,BigDecimal.ROUND_DOWN));
        this.updateById(erpOrderEntity);
        //添加操作日志
        ErpOrderLogEntity erpOrderLogEntity = new ErpOrderLogEntity();
        erpOrderLogEntity.setLogText("删除商品，商品productId:"+erpOrderItemEntity.getProductId());
        erpOrderLogEntity.setOrderNo(erpOrderEntity.getOrderNo());
        erpOrderLogEntity.setCreateTime(new Date());
        erpOrderLogEntity.setCreateName(UserUtils.getCurentUser().getUsername());
        erpOrderLogService.save(erpOrderLogEntity);
        return R.ok();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R addFastGoods(ErpOrderItemDto erpOrderItemDto) {
        String orderNo = erpOrderItemDto.getErpOrder().getOrderNo();
        ErpOrderEntity erpOrder = this.getById(orderNo);
        if(erpOrder.getProductionStatus()!=ProductionStatusEnum.NEW_ORDER.toInt()&&erpOrder.getProductionStatus()!=ProductionStatusEnum.IN_PRODUCTION.toInt()){
            return  R.error("该订单生产状态为"+"'"+EnumUtil.getEnumByCodeInt(ProductionStatusEnum.class,erpOrder.getProductionStatus()).toDescribe()+"',"+"无法新增商品!");
        }
        Long sellerId = UserUtils.getCurentUser().getSellerId();
        //用List接收前台传过来的商品，但实际上只会有一个商品
        List<ErpOrderItemEntity> erpOrderItemList = erpOrderItemDto.getErpOrderItemList();
        ErpOrderItemEntity erpOrderItemEntity= erpOrderItemList.get(0);
        erpOrderItemEntity.setOrderNo(orderNo);
        erpOrderItemEntity.setItemDel(0);
        erpOrderItemEntity.setItemType(OrderItemTypeEnum.PRODUCT.toCode());
        //待分配
        erpOrderItemEntity.setStatus(OrderItemStatusEnum.UN_ALLOTED.toInt());
        //根据订单号查询会员id以及
        //查询storeMember表是否存在此客户
        StoreMemberEntity storeMemberEntity = storeMemberService.getOne(new QueryWrapper<StoreMemberEntity>().eq("member_id", erpOrder.getMemberId())
                .eq("seller_id",UserUtils.getCurentUser().getSellerId()));
        //查询出之前所有订单详情

        //根据订单号得到之前所有订单明细
        List<ErpOrderItemEntity> erpOrderItemEntityList = erpOrderItemService.list(new QueryWrapper<ErpOrderItemEntity>().eq("order_no", orderNo).eq("item_del", 0));
        erpOrderItemEntityList.add(erpOrderItemEntity);
        //定义一个变量接收商品总值
        BigDecimal totalAmount=new BigDecimal(0);
        //定义一个变量接收订单应付金额
        BigDecimal payableAmount=new BigDecimal(0);
        //先重新计算出所有商品的总额
        for (int i=0;i<erpOrderItemEntityList.size();i++){
            ErpOrderItemEntity erpOrderItem=erpOrderItemEntityList.get(i);
            BigDecimal amount = erpOrderItem.getAmount();
            totalAmount=totalAmount.add(amount);
            //如果为报价商品
            if(erpOrderItem.getAddcartBuyType().equals(AddcartBuyTypeEnum.PRINT.toCode())||erpOrderItem.getAddcartBuyType().equals(AddcartBuyTypeEnum.FAST.toCode())){
                payableAmount=payableAmount.add(getNotStandardTotalAmount(erpOrderItem,storeMemberEntity));
            }else{
                //按标品计算
                payableAmount=payableAmount.add(getTotalAmount(erpOrderItem,storeMemberEntity));
            }
        }
        //优惠金额，为正数
        BigDecimal pmtGoods=totalAmount.subtract(payableAmount);
        //修改优惠金额
        erpOrder.setPmtGoods(pmtGoods);
        //应付金额=调价+应付金额
        BigDecimal discount = erpOrder.getDiscount();
        if(discount!=null){
            payableAmount=erpOrder.getDiscount().add(payableAmount);
        }
        erpOrder.setPayableAmount(payableAmount.setScale(2,BigDecimal.ROUND_DOWN));
        erpOrder.setTotalAmount(totalAmount.setScale(2,BigDecimal.ROUND_DOWN));
        erpOrderItemService.save(erpOrderItemEntity);
        this.updateById(erpOrder);
        //添加操作日志
        ErpOrderLogEntity erpOrderLogEntity = new ErpOrderLogEntity();
        if(erpOrderItemList.get(0).getAddcartBuyType().equals("fast")){
            erpOrderLogEntity.setLogText("添加快印商品");
        }
        if(erpOrderItemList.get(0).getAddcartBuyType().equals("print")){
            erpOrderLogEntity.setLogText("添加商务印刷商品");
        }
        erpOrderLogEntity.setOrderNo(orderNo);
        erpOrderLogEntity.setCreateTime(new Date());
        erpOrderLogEntity.setCreateName(UserUtils.getCurentUser().getUsername());
        erpOrderLogService.save(erpOrderLogEntity);
        return R.ok();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R addPrintGoods(ErpOrderItemDto erpOrderItemDto) {
        return this.addFastGoods(erpOrderItemDto);
    }

    /**
     * 保存标品中的数据（标品，广告物料）
     *
     * @param erpOrderItemDto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R addStandardGoods(ErpOrderItemDto erpOrderItemDto) {
        String orderNo = erpOrderItemDto.getErpOrder().getOrderNo();
        ErpOrderEntity erpOrder = this.getById(orderNo);
        if(erpOrder.getProductionStatus()!=ProductionStatusEnum.NEW_ORDER.toInt()&&erpOrder.getProductionStatus()!=ProductionStatusEnum.IN_PRODUCTION.toInt()){
            return  R.error("该订单生产状态为"+"'"+EnumUtil.getEnumByCodeInt(ProductionStatusEnum.class,erpOrder.getProductionStatus()).toDescribe()+"',"+"无法新增商品!");
        }
        List<ErpOrderItemEntity> erpOrderItemList = erpOrderItemDto.getErpOrderItemList();
        //根据订单号查询会员id以及
        //查询storeMember表是否存在此客户
        StoreMemberEntity storeMemberEntity = storeMemberService.getOne(new QueryWrapper<StoreMemberEntity>().eq("member_id", erpOrder.getMemberId()));
        //商户id
        Long sellerId = UserUtils.getCurentUser().getSellerId();
        BigDecimal amount = new BigDecimal(0);

        //定义变量记录此次添加商品总额，用于计算优惠金额
        BigDecimal goodsAmount = new BigDecimal(0);
        for (int i = 0; i < erpOrderItemList.size(); i++) {
            goodsAmount = goodsAmount.add(erpOrderItemList.get(i).getAmount());
        }
        //新增商品总额
        BigDecimal addPayableAmount = new BigDecimal(0);
        for (int i = 0; i < erpOrderItemList.size(); i++) {
            ErpOrderItemEntity erpOrderItem = erpOrderItemList.get(i);
            if(!erpOrderItem.getAddcartBuyType().equals("fast")&& !erpOrderItem.getAddcartBuyType().equals("print")){
                //先根据productId找到OrigProductId
                StoreGoodsProductEntity storeGoodsProductEntity = storeGoodsProductService.getById(erpOrderItem.getProductId());
                if(storeGoodsProductEntity!=null){
                    if(storeGoodsProductEntity.getOrigProductId()!=null){
                        GoodsProductEntity goodsProductEntity = goodsProductService.getById(storeGoodsProductEntity.getOrigProductId());
                        if(goodsProductEntity!=null){
                            erpOrderItem.setGoodsId(goodsProductEntity.getGoodsId().intValue());
                        }
                    }
                }
            }
            //判断门店是否存在对应商品的优惠
            StoreProductPriceEntity storeProductPrice = storeProductPriceService.getOne(new QueryWrapper<StoreProductPriceEntity>().eq("product_id", erpOrderItem.getProductId())
                    .eq("seller_id", sellerId));
            if (storeProductPrice == null) {
                amount = erpOrderItem.getNums().multiply(erpOrderItem.getPrice());
            } else {
                amount = getTotalAmount(erpOrderItem, storeMemberEntity);
            }
            erpOrderItem.setOrderNo(orderNo);
           // erpOrderItem.setAmount(amount);
            //统计应付金额
            BigDecimal total = addPayableAmount.add(amount);
            addPayableAmount = total;
            erpOrderItem.setItemDel(0);
            erpOrderItem.setItemType(OrderItemTypeEnum.PRODUCT.toCode());
            //待分配
            erpOrderItem.setStatus(OrderItemStatusEnum.UN_ALLOTED.toInt());
        }

        if (erpOrderItemList.size() > 0) {
            erpOrderItemService.saveBatch(erpOrderItemList);
        }
        //新商品的优惠金额
        BigDecimal newPmtGoods = goodsAmount.subtract(addPayableAmount);
        if(erpOrder.getPmtGoods()==null){
            erpOrder.setPmtGoods(new BigDecimal(0));
        }
        erpOrder.setPmtGoods(erpOrder.getPmtGoods().add(newPmtGoods));
        erpOrder.setTotalAmount(erpOrder.getTotalAmount().add(goodsAmount).setScale(2,BigDecimal.ROUND_DOWN));
        erpOrder.setPayableAmount(erpOrder.getPayableAmount().add(addPayableAmount).setScale(2,BigDecimal.ROUND_DOWN));
        //修改订单
        this.updateById(erpOrder);

        //添加操作日志
        ErpOrderLogEntity erpOrderLogEntity = new ErpOrderLogEntity();
        erpOrderLogEntity.setLogText("添加标品");
        erpOrderLogEntity.setOrderNo(orderNo);
        erpOrderLogEntity.setCreateTime(new Date());
        erpOrderLogEntity.setCreateName(UserUtils.getCurentUser().getUsername());
        erpOrderLogService.save(erpOrderLogEntity);
        return R.ok();
    }

    //标品数据复制到order_info以及orderInfo_item
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean copyToOrderInfo(Integer eoItemId) {
        boolean flag = true;
        //先查询erpOrder数据封装到OrderInfo
        //查询erp_order_item数据封装到orderItem;
        ErpOrderItemEntity erpOrderItemEntity = erpOrderItemService.getById(eoItemId);
        String orderNo = erpOrderItemEntity.getOrderNo();
        ErpOrderEntity erpOrderEntity = this.getById(orderNo);
        //紫云网订单order_info表中存在，无需同步
        if(erpOrderEntity.getOrderSource()==OrderSourceEnum.ZIYUN.toInt()){
            return true;
        }
        //判断orderInfo表中是否已经存在
        OrderInfoEntity orderInfo = orderInfoService.getById(orderNo);
        if (orderInfo == null) {
            OrderInfoEntity orderInfoEntity = ErpOrderUtils.erpToZiyunOrder(erpOrderEntity);
            //保持数据到orderInfo表以及Order_item表
            orderInfoService.save(orderInfoEntity);
        }
        //根据productID查询紫云网productID
        StoreGoodsProductEntity storeGoodsProductEntity = storeGoodsProductService.getById(erpOrderItemEntity.getProductId());
        if(storeGoodsProductEntity==null){
            throw new RRException("商品productId为0，请联系管理员!");
        }
        GoodsProductEntity goodsProductEntity = goodsProductService.getOne(new QueryWrapper<GoodsProductEntity>().eq("date_flag", 0).eq("product_id", storeGoodsProductEntity.getOrigProductId()));
        if(erpOrderItemEntity.getOriginalItemId()==null){
            OrderItemEntity orderItemEntity = ErpOrderUtils.erpToZiyunOrderItem(erpOrderItemEntity, orderNo);
            orderItemEntity.setProductId(storeGoodsProductEntity.getOrigProductId());
            if(goodsProductEntity!=null) {
                orderItemEntity.setGoodsId(goodsProductEntity.getGoodsId());
            }
            orderItemService.save(orderItemEntity);
            erpOrderItemEntity.setOriginalItemId(orderItemEntity.getItemId());
            flag=erpOrderItemService.updateById(erpOrderItemEntity);
        }else{
            OrderItemEntity orderItemEntity = orderItemService.getById(erpOrderItemEntity.getOriginalItemId());
            erpOrderItemEntity.setOriginalItemId(orderItemEntity.getItemId());
            orderItemEntity.setProductId(storeGoodsProductEntity.getOrigProductId());
            if(goodsProductEntity!=null){
                orderItemEntity.setGoodsId(goodsProductEntity.getGoodsId());
            }
            flag = orderItemService.updateById(orderItemEntity);
        }
        return flag;
    }


    /**
     * 计算标品明细商品总价
     * 1.会员是否有账套，无账套则不存在打折以及产品优惠
     * 2.会员有账套
     * a.根据账套查询当前商品的折扣率以及阶梯价
     * b.如果阶梯价存在，
     * c.根据数量取阶梯价,取阶梯价，不存在取price
     * d.判断当前账套下 ，当前产品是否存在阶梯折扣
     */
    private BigDecimal getTotalAmount(ErpOrderItemEntity erpOrderItemEntity, StoreMemberEntity storeMember) {
        Long sellerId = UserUtils.getCurentUser().getSellerId();
        if(storeMember.getMemberId().equals("898855")){
            sellerId=20L;
        }
        Integer productId = erpOrderItemEntity.getProductId();
        BigDecimal nums = erpOrderItemEntity.getNums();
        //定义总价变量接收最终结果
        BigDecimal totalAmount = erpOrderItemEntity.getAmount();
        //根据product_id去查询
        StoreGoodsProductEntity storeGoodsProductEntity = storeGoodsProductService.getById(productId);
        if(storeGoodsProductEntity==null){
            throw new RRException("商品不存在导致算价错误");
        }
        //先查询store_product_price,获取不同数量的阶梯价
        StoreProductPriceEntity storeProductPrice = storeProductPriceService.getOne(new QueryWrapper<StoreProductPriceEntity>().eq("seller_id", sellerId).eq("product_id", productId).eq("del", 0));
        //判断账套有没有过期
        StoreFavouredPriceEntity storeFavouredPrice = storeFavouredPriceService.getOne(new QueryWrapper<StoreFavouredPriceEntity>().
                eq("favoured_id", storeMember.getPriceSet()).eq("del_flag", 0).gt("end_time",new Date()));
        if(storeFavouredPrice==null){
            storeMember.setPriceSet(null);
        }
        if (storeMember.getPriceSet() == null) {
                //判断是否为广告物料，以及是否为按周长按面积
                if (erpOrderItemEntity.getAddcartBuyType().equals(AddcartBuyTypeEnum.MATERIAL.toCode())) {
                    //判断是按周长还是按面积
                    if(erpOrderItemEntity.getPricingManner()==null){
                        erpOrderItemEntity.setPricingManner(storeGoodsProductEntity.getPricingManner());
                    }
                    //如果按周长或者按长度
                    if (erpOrderItemEntity.getPricingManner()==1||erpOrderItemEntity.getPricingManner()==2) {
                        if(erpOrderItemEntity.getEoItemId()!=null&&erpOrderItemEntity.getLength()==null){
                            //从属性中截取
                            String str=erpOrderItemEntity.getAddon().substring(erpOrderItemEntity.getAddon().lastIndexOf(":")+1);
                            BigDecimal length=new BigDecimal(str);
                            erpOrderItemEntity.setLength(length);
                        }
                        nums = erpOrderItemEntity.getLength().multiply(nums);

                    } else {
                        //从属性中截取
                        if(erpOrderItemEntity.getEoItemId()!=null&&erpOrderItemEntity.getLength()==null){
                            //从属性中截取
                            String str=erpOrderItemEntity.getAddon().substring(erpOrderItemEntity.getAddon().lastIndexOf(":")+1);
                            String[] split = str.split("\\*");
                            BigDecimal length=new BigDecimal(split[0]);
                            BigDecimal width=new BigDecimal(split[1]);
                            erpOrderItemEntity.setLength(length);
                            erpOrderItemEntity.setWidth(width);
                        }
                            nums = erpOrderItemEntity.getLength().multiply(erpOrderItemEntity.getWidth()).multiply(nums);

                    }
            }
            totalAmount = nums.multiply(erpOrderItemEntity.getPrice());

        } else {
            //判断是否为广告物料，以及是否为按周长按面积
            if (erpOrderItemEntity.getAddcartBuyType().equals(AddcartBuyTypeEnum.MATERIAL.toCode())) {
                //判断是按周长还是按面积
                if(erpOrderItemEntity.getPricingManner()==null){

                    erpOrderItemEntity.setPricingManner(storeGoodsProductEntity.getPricingManner());
                }
                //如果按周长
                if (erpOrderItemEntity.getPricingManner()==1||erpOrderItemEntity.getPricingManner()==2) {
                    if(erpOrderItemEntity.getEoItemId()!=null&&erpOrderItemEntity.getLength()==null){
                        //从属性中截取
                        String str=erpOrderItemEntity.getAddon().substring(erpOrderItemEntity.getAddon().length()-1);
                        BigDecimal length=new BigDecimal(str);
                        erpOrderItemEntity.setLength(length);
                    }
                    nums = erpOrderItemEntity.getLength().multiply(nums);
                } else {
                    //从属性中截取
                    if(erpOrderItemEntity.getEoItemId()!=null&&erpOrderItemEntity.getLength()==null){
                        //从属性中截取
                        String str=erpOrderItemEntity.getAddon().substring(erpOrderItemEntity.getAddon().length()-3);
                        BigDecimal length=new BigDecimal(str.substring(0,1));
                        BigDecimal width=new BigDecimal(str.substring(2));
                        erpOrderItemEntity.setLength(length);
                        erpOrderItemEntity.setWidth(width);
                    }
                    nums = erpOrderItemEntity.getLength().multiply(erpOrderItemEntity.getWidth()).multiply(nums);
                }
            }
            //定义一个price用于接收最终价格
            BigDecimal price = erpOrderItemEntity.getPrice();


            //阶梯价存在
            if (StringUtils.isNotBlank(storeProductPrice.getStepPrice()) && (NumberUtils.isContainNumber(storeProductPrice.getStepPrice()))) {
                String stepPrice = storeProductPrice.getStepPrice();
                //解析阶梯价
                List<StepPriceEntity> stepPricelist = JsonUtils.string2Collection(stepPrice, List.class, StepPriceEntity.class);

                for (int i = 0; i < stepPricelist.size(); i++) {
                    StepPriceEntity stepPriceEntity = stepPricelist.get(i);
                    //如果数量处于阶梯价格之间
                    if ((stepPriceEntity.getMaxSum().compareTo(nums) >= 0) && (stepPriceEntity.getMinSum().compareTo(nums) <= 0)) {
                        price = stepPriceEntity.getPrice();
                        //计算出总价
                        totalAmount = price.multiply(nums);
                        return totalAmount;
                    }
                }
            }
            //先查询当前账套下当前产品是否存在折扣率以及阶梯价
            StoreFavouredPriceDetailEntity storeFavouredPriceDetailEntity = storeFavouredPriceDetailService.getOne(new QueryWrapper<StoreFavouredPriceDetailEntity>().eq("favoured_id", storeMember.getPriceSet())
                    .eq("product_id", productId).eq("del_flag", 0));

            //如果存在
            if (storeFavouredPriceDetailEntity != null) {
                //如果存在阶梯折扣
                if (StringUtils.isNotBlank(storeFavouredPriceDetailEntity.getStepPrice())&&NumberUtils.isContainNumber(storeFavouredPriceDetailEntity.getStepPrice())) {
                    //取阶梯折扣价
                    String stepPrice = storeFavouredPriceDetailEntity.getStepPrice();
                    //解析阶梯价
                    List<StepPriceEntity> stepPricelist = JsonUtils.string2Collection(stepPrice, List.class, StepPriceEntity.class);
                    for (int i = 0; i < stepPricelist.size(); i++) {
                        StepPriceEntity stepPriceEntity = stepPricelist.get(i);
                        //如果总价处于阶梯价格之间
                        if ((stepPriceEntity.getBeginNum().compareTo(totalAmount) <= 0) && (stepPriceEntity.getEndNum().compareTo(totalAmount) >= 0)) {
                            BigDecimal discountRate = stepPriceEntity.getSinglePrice();
                            totalAmount = totalAmount.multiply(discountRate);
                            break;
                        }
                    }
                } else {
                    totalAmount = totalAmount.multiply(storeFavouredPriceDetailEntity.getDiscountRate());
                }
            } else {
                    totalAmount = totalAmount.multiply(storeFavouredPrice.getDiscountRate());
                }
            }
        if(totalAmount.compareTo(storeProductPrice.getStartPrice())<0){
            totalAmount=storeProductPrice.getStartPrice();
        }
        return totalAmount;
    }


    /**
     * 计算非标品明细商品总价
     */
    private BigDecimal getNotStandardTotalAmount(ErpOrderItemEntity erpOrderItemEntity, StoreMemberEntity storeMember) {
        //总价
        BigDecimal totalAmount = erpOrderItemEntity.getAmount();
        Long sellerId=UserUtils.getCurentUser().getSellerId();
        //如果是分配memberID=898855,特殊处理
        if(storeMember.getMemberId().equals("898855")){
            sellerId=20L;
        }
        //判断会员有无价格账套，无价格账套则不存在优惠
        if(storeMember.getPriceSet()==null){
            return totalAmount;
        }
        //会员存在价格账套，根据账套取出折扣率
        StoreFavouredPriceEntity storeFavouredPriceEntity = storeFavouredPriceService.getOne(new QueryWrapper<StoreFavouredPriceEntity>().eq("favoured_id", storeMember.getPriceSet())
                .eq("del_flag", 0).eq("seller_id",sellerId).gt("end_time",new Date()));
        if(storeFavouredPriceEntity==null){
            return totalAmount;
        }
        //门店价格折扣
        BigDecimal discount=storeFavouredPriceEntity.getDiscountRate();
        if(discount==null){
            discount=new BigDecimal(1);
        }
        //存在价格账套
        Integer favouredId=storeMember.getPriceSet();
        //根据此报价商品的紫云网分类id去查找门店分类id
        Integer productId = erpOrderItemEntity.getProductId();
        StoreGoodsCategoryEntity storeGoodsCategoryEntity = storeGoodsCategoryService.getOne(new QueryWrapper<StoreGoodsCategoryEntity>().eq("ziyun_category_id", productId)
                .eq("del", 0));
        //如果不存在分类的折扣，就根据会员折扣判断
        if(storeGoodsCategoryEntity==null){
            return totalAmount.multiply(discount);
        }else{
            //找到门店分类id
            Integer categoryId = storeGoodsCategoryEntity.getCategoryId();
            //根据分类找到折扣率以及阶梯折扣

            Map<String,Object> params=new HashMap<>();
            params.put("sellerId",sellerId);
            params.put("categoryId",categoryId);
            params.put("favouredId",favouredId);
            List<StoreFavouredPriceDetailEntity> storeFavouredPriceDetailList= storeFavouredPriceDetailService.getStoreFavouredPriceDetail(params);
            if(storeFavouredPriceDetailList.size()==0){
                //不存在此分类的优惠
                return totalAmount.multiply(discount);
            }else{
                //存在此分类的优惠
                StoreFavouredPriceDetailEntity storeFavouredPriceDetail = storeFavouredPriceDetailList.get(0);

                //如果存在阶梯价优惠
                if(StringUtils.isNotBlank(storeFavouredPriceDetail.getStepPrice())){
                    try {
                        String stepPrice=storeFavouredPriceDetail.getStepPrice();
                        List<StepPriceEntity> stepPriceList=JsonUtils.string2Collection(stepPrice,List.class,StepPriceEntity.class);
                        for (int i=0;i<stepPriceList.size();i++){
                            StepPriceEntity stepPriceEntity=stepPriceList.get(i);
                            if(totalAmount.compareTo(stepPriceEntity.getBeginNum())>=0&&totalAmount.compareTo(stepPriceEntity.getEndNum())<=0){
                                discount=stepPriceEntity.getSinglePrice();
                                break;
                            }
                        }
                        return totalAmount.multiply(discount);
                    }catch (Exception e){
                        //不处理
                    }finally {
                        //如果不存在阶梯优惠，则按照分类的优惠来
                        discount=storeFavouredPriceDetail.getDiscountRate();
                        if(discount==null){
                            discount=new BigDecimal(1);
                        }
                        return  totalAmount=totalAmount.multiply(discount);
                    }
                }else{
                    //如果不存在阶梯优惠，则按照分类的优惠来
                    discount=storeFavouredPriceDetail.getDiscountRate();
                    return  totalAmount=totalAmount.multiply(discount);
                }
            }
        }
    }

    @Override
    public ErpOrderEntity getErpOrder(String orderNo) {
        return this.baseMapper.getErpOrder(orderNo);
    }

    /**
     * 紫云网订单撤回
     * @param orderNo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R ziyunOrderBack(String orderNo) {
        if(StringUtils.isBlank(orderNo)){
            return R.error("参数异常，请联系管理员!");
        }
        //先查询当前订单是否为分配订单
        ErpOrderAllotRelevanceEntity erpOrderAllotRelevanceEntity = erpOrderAllotRelevanceService.getOne(new QueryWrapper<ErpOrderAllotRelevanceEntity>()
                .eq("order_allot_no", orderNo).eq("del", DeleteEnum.NOT_DELETE.toInt()));
        if(erpOrderAllotRelevanceEntity==null){
            return R.error("非紫云网分配订单无法撤回!");
        }
        //删除erp_order以及erp_order_item中信息
        //删除erp_order_allot_relevance,erp_order_production中信息
        List<ErpOrderItemEntity> erpOrderItemlist = erpOrderItemService.list(new QueryWrapper<ErpOrderItemEntity>().eq("order_no", orderNo).eq("item_del", DeleteEnum.NOT_DELETE.toInt()));
        for(int i=0;i<erpOrderItemlist.size();i++){
            //修改状态为删除
            erpOrderItemlist.get(i).setItemDel(1);
        }
        ErpOrderEntity erpOrderEntity = this.getById(orderNo);
        erpOrderEntity.setProductionStatus(ProductionStatusEnum.CANCELLED.toInt());
        //删除生产单
        Integer productionId = erpOrderAllotRelevanceEntity.getProductionId();
        ErpOrderProductionEntity erpOrderProductionEntity = erpOrderProductionService.getById(productionId);
        if(erpOrderProductionEntity!=null){
            erpOrderProductionEntity.setDel(DeleteEnum.DELETE.toInt());
            erpOrderProductionEntity.setUpdateTime(new Date());
            erpOrderProductionEntity.setUpdateName(UserUtils.getCurentUser().getUsername());
            //4为取消
            erpOrderProductionEntity.setProductionStatus(4);
            erpOrderProductionService.updateById(erpOrderProductionEntity);
            //如果为订单分配,则还需要修改erp_order表中信息以及erp_orderItem表中信息
            String allotType = erpOrderProductionEntity.getAllotType();
            //原始单号
            String erpOrderOrderNo=erpOrderProductionEntity.getOrderNo();
            //原始订单
            ErpOrderEntity orderEntity = this.getById(erpOrderOrderNo);
            if(orderEntity!=null) {
                //原始订单商品明细
                List<ErpOrderItemEntity> itemList = erpOrderItemService.list(new QueryWrapper<ErpOrderItemEntity>().eq("order_no", erpOrderOrderNo).eq("item_del", DeleteEnum.NOT_DELETE.toInt()));
                if(allotType.equals(AllotTypeEnum.ORDER.toCode())){
                    //将原始订单状态改为待分配
                    orderEntity.setProductionStatus(ProductionStatusEnum.UN_ALLOT.toInt());
                    for (int i=0;i<itemList.size();i++){
                        ErpOrderItemEntity erpOrderItemEntity = itemList.get(i);
                        erpOrderItemEntity.setStatus(OrderItemStatusEnum.UN_ALLOTED.toInt());
                    }
                    //修改原始订单为待分配
                    this.updateById(orderEntity);
                    if(itemList.size()>0){
                        erpOrderItemService.updateBatchById(itemList);
                    }
                }else{
                    //如果为商品分配，需要判断其他商品的状态是否为待分配，
                    // 为待分配则修改erp_order为待分配。如果不是所有商品为待分配，则不修改erp_order信息
                    //查询这条订单的所有商品分配信息
                    List<ErpOrderAllotRelevanceEntity> allAllotList = erpOrderAllotRelevanceService.list(new QueryWrapper<ErpOrderAllotRelevanceEntity>()
                            .eq("original_order_no", erpOrderOrderNo).eq("del", DeleteEnum.NOT_DELETE.toInt()));
                    //如果所有分配信息大于这条订单撤回的商品数量，则不修改订单状态,但商品状态都需要改回未分配
                    if(allAllotList.size()==erpOrderItemlist.size()){
                        //将原始订单状态改为待分配
                        orderEntity.setProductionStatus(ProductionStatusEnum.UN_ALLOT.toInt());
                        for (int i=0;i<itemList.size();i++){
                            ErpOrderItemEntity erpOrderItemEntity = itemList.get(i);
                            erpOrderItemEntity.setStatus(OrderItemStatusEnum.UN_ALLOTED.toInt());
                        }
                        //修改原始订单为待分配
                        this.updateById(orderEntity);
                        if(itemList.size()>0){
                            erpOrderItemService.updateBatchById(itemList);
                        }
                    }else if(allAllotList.size()>erpOrderItemlist.size()){
                        for (int i=0;i<itemList.size();i++){
                            ErpOrderItemEntity erpOrderItemEntity = itemList.get(i);
                            erpOrderItemEntity.setStatus(OrderItemStatusEnum.UN_ALLOTED.toInt());
                        }
                        if(itemList.size()>0){
                            erpOrderItemService.updateBatchById(itemList);
                        }
                    }else{
                        throw  new RRException("分配信息缺失，请联系管理员!");
                    }
                }
                try {
                    //order_info表中的这条分配订单也要作废掉
                    logger.info("================= order cancel api start==================");
                    Set<String> orderIds = New.hashSet(1);
                    orderIds.add(orderNo);
                    OrderCancelBatchParamDto orderCancelBatchParamDto = OrderCancelBatchParamDto.builder()
                            .orderIds(orderIds)
                            .userId(Long.valueOf(erpOrderEntity.getMemberId()))
                            .build();
                    logger.info("================= order cancel api param：{}", JsonUtils.object2String(orderCancelBatchParamDto));
                    OrderResult<?> orderResult = microOrderService.updateOrderCancelBatch(orderCancelBatchParamDto);
                    logger.info("================= order cancel api result :{}", JsonUtils.object2String(orderResult));
                }catch (Exception e){
                    e.printStackTrace();
                    throw new RRException("撤回紫云网订单失败");
                }
                //删除分配过来的订单
                this.updateById(erpOrderEntity);
                //删除订单商品
                if(erpOrderItemlist.size()>0){
                    erpOrderItemService.updateBatchById(erpOrderItemlist);
                }
                //删除分配关联单
                erpOrderAllotRelevanceEntity.setDel(DeleteEnum.DELETE.toInt());
                erpOrderAllotRelevanceService.updateById(erpOrderAllotRelevanceEntity);
                //添加操作日志
                ErpOrderLogEntity erpOrderLogEntity=new ErpOrderLogEntity();
                erpOrderLogEntity.setLogText("撤回紫云网订单,订单号:"+orderNo);
                erpOrderLogEntity.setCreateName(UserUtils.getCurentUser().getUsername());
                erpOrderLogEntity.setCreateTime(new Date());
                erpOrderLogEntity.setOrderNo(orderNo);
                erpOrderLogService.save(erpOrderLogEntity);
            }
        }else{
            return R.error("未找到生产单信息，无法进行撤回!请联系管理员!");
        }
        return R.ok();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R startUpdatePrice(ErpOrderItemDto erpOrderItemDto) {
        if(erpOrderItemDto.getErpOrderItemList().size()==0){
            return R.error("没有商品可以进行调价!");
        }
        String orderNo=erpOrderItemDto.getErpOrderItemList().get(0).getOrderNo();
       if(!isErpOrder(orderNo)){
           return R.error("非门店订单无法进行调价");
       }
        //添加操作日志
        ErpOrderLogEntity erpOrderLogEntity=new ErpOrderLogEntity();
       //定义字符串接收日志
       StringBuilder sb=new StringBuilder();
        ErpOrderEntity erpOrderEntity = this.getById(orderNo);
        List<ErpOrderItemEntity> erpOrderItemList = erpOrderItemDto.getErpOrderItemList();
        BigDecimal totalAmount=new BigDecimal(0);
        for(int i=0;i<erpOrderItemList.size();i++){
            ErpOrderItemEntity erpOrderItemEntity=erpOrderItemList.get(i);
            totalAmount=totalAmount.add(erpOrderItemEntity.getAmount());
            sb.append("eoitemId:"+erpOrderItemEntity.getEoItemId()).append("单价:"+erpOrderItemEntity.getPrice())
              .append("总价:"+erpOrderItemEntity.getAmount()).append(";");
        }
        erpOrderEntity.setTotalAmount(totalAmount);
        BigDecimal pmtGoods = erpOrderEntity.getPmtGoods();
        if(pmtGoods==null){
            erpOrderEntity.setPayableAmount(totalAmount);
        }else{
            erpOrderEntity.setPayableAmount(totalAmount.subtract(pmtGoods));
        }
        BigDecimal discount=erpOrderEntity.getDiscount();
        if(discount==null){
            erpOrderEntity.setPayableAmount(totalAmount);
        }else{
            erpOrderEntity.setPayableAmount(totalAmount.add(discount));
        }
        this.updateById(erpOrderEntity);
        erpOrderItemService.updateBatchById(erpOrderItemList);
        erpOrderLogEntity.setLogText("业务员修改商品详情金额:"+sb.toString());
        erpOrderLogEntity.setCreateName(UserUtils.getCurentUser().getUsername());
        erpOrderLogEntity.setCreateTime(new Date());
        erpOrderLogEntity.setOrderNo(orderNo);
        erpOrderLogService.save(erpOrderLogEntity);
        return R.ok();
    }

    @Override
    public R updatePmtGoodsAndProjectName(ErpOrderEntity erpOrder) {
        String orderNo=erpOrder.getOrderNo();
        BigDecimal pmtGoods=erpOrder.getPmtGoods();
        ErpOrderEntity erpOrderEntity = this.getById(orderNo);
        erpOrderEntity.setPmtGoods(pmtGoods);
        erpOrderEntity.setPayableAmount(erpOrderEntity.getTotalAmount().subtract(pmtGoods));
        erpOrderEntity.setProjectName(erpOrder.getProjectName());
        this.updateById(erpOrderEntity);
        //添加操作日志
        ErpOrderLogEntity erpOrderLogEntity=new ErpOrderLogEntity();
        erpOrderLogEntity.setLogText("业务员修改订单优惠,金额"+pmtGoods+";修改项目名称为:"+pmtGoods);
        erpOrderLogEntity.setCreateName(UserUtils.getCurentUser().getUsername());
        erpOrderLogEntity.setCreateTime(new Date());
        erpOrderLogEntity.setOrderNo(orderNo);
        erpOrderLogService.save(erpOrderLogEntity);
        return R.ok();
    }

    //判断是否为紫云网分配过来订单
    public boolean isAllot(String orderNo){
        List<ErpOrderProductionEntity> productionOrderList = erpOrderProductionService.list(new QueryWrapper<ErpOrderProductionEntity>().eq("production_order", orderNo));
        if(productionOrderList.size()>0){
            return true;
        }else{
            return  false;
        }
    }

    //判断是否为erp订单
    @Override
    public Boolean isErpOrder(String orderNo){
        ErpOrderEntity erpOrderEntity = this.getById(orderNo);
        if(erpOrderEntity.getOrderSource()==OrderSourceEnum.OFFlINE.toInt()){
            return true;
        }else{
            return  false;
        }
    }


    @Override
    public R confirmCost(String orderNo) {
        ErpOrderEntity erpOrderEntity = this.getById(orderNo);
        erpOrderEntity.setCommissionStatus(CommissionStatusEnum.Entered.toInt());
        this.updateById(erpOrderEntity);
        ErpOrderLogEntity erpOrderLogEntity=new ErpOrderLogEntity();
        erpOrderLogEntity.setOrderNo(orderNo);
        erpOrderLogEntity.setCreateTime(new Date());
        erpOrderLogEntity.setLogText("确认成本录入完成");
        erpOrderLogEntity.setCreateName(UserUtils.getCurentUser().getUsername());
        erpOrderLogService.save(erpOrderLogEntity);
        return R.ok();
    }

    @Override
    public R batchEnter(String ids, String createName, String createBy) {
        Map<String,Object> map=new HashMap<>();
        String[] split = ids.split(",");
        List<String> idList=new ArrayList<>();
        for (int i=0;i<split.length;i++){
            idList.add(split[i]);
        }
        List<ErpOrderEntity> erpOrderEntities = (List<ErpOrderEntity>) this.listByIds(idList);
        //判断是否所有订单都为已完成
        for (int i=0;i<erpOrderEntities.size();i++){
            if(erpOrderEntities.get(i).getProductionStatus()!=ProductionStatusEnum.FINISH.toInt()){
                return R.error("请检查所选订单生产状态是否均为 '已完成' 状态!只有已完成才能进行成本录入");
            }
        }
        //判断是否所有订单都为未录入
        for (int i=0;i<erpOrderEntities.size();i++){
            if(erpOrderEntities.get(i).getCommissionStatus()!=CommissionStatusEnum.NOTENTERED.toInt()){
                return R.error("请检查所选订单成本状态是否均为未录入状态!");
            }
        }
        map.put("commissionStatus",CommissionStatusEnum.Entered.toInt());
        this.baseMapper.batchEnter(map, idList);
        //添加订单日志
        List<ErpOrderLogEntity> orderLogEntityList=new ArrayList<>();
        for (int i = 0; i <idList.size(); i++) {
            String orderNo = idList.get(i);
            ErpOrderLogEntity erpOrderLogEntity=new ErpOrderLogEntity();
            erpOrderLogEntity.setOrderNo(orderNo);
            erpOrderLogEntity.setCreateBy(createBy);
            erpOrderLogEntity.setCreateName(createName);
            erpOrderLogEntity.setCreateTime(new Date());
            erpOrderLogEntity.setLogText("pop批量录入");
            orderLogEntityList.add(erpOrderLogEntity);
        }
        if(orderLogEntityList.size()>0){
            erpOrderLogService.saveBatch(orderLogEntityList);
        }
        return R.ok();
    }


    /**************************图文宝**********************************/
    @Override
    public R queryPageTwbOrderList(Map<String, Object> params) {
        Page<ErpOrderEntity> page = new Page<>(Integer.parseInt(params.get("page").toString()), Integer.parseInt(params.get("limit").toString()));
       Integer current= Integer.parseInt(params.get("page").toString());

        Integer limit= Integer.parseInt(params.get("limit").toString());
        if(current>0){
            current--;
        }
        params.put("current",current*limit);
        List<ErpOrderEntity> erpOrderEntities = this.baseMapper.querytTwbPageErpOrderList(params);
        page.setRecords(erpOrderEntities);
        Integer total=  this.baseMapper.selectTwbTotal(params);
        page.setTotal(total);
        PageUtils pageUtils = new PageUtils(page);
        //查询当天订单总数
        List<BigDecimal> dayCount= this.baseMapper.getDayCount(params);
        BigDecimal dayMoney=new BigDecimal(0);
        BigDecimal monthMoney=new BigDecimal(0);
        BigDecimal yearMoney=new BigDecimal(0);
        for (int i=0;i<dayCount.size();i++){
            dayMoney=  dayMoney.add(dayCount.get(i));
        }
        //查询当月订单总数
        List<BigDecimal> monthCount= this.baseMapper.getMonthCount(params);
        for (int i=0;i<monthCount.size();i++){
            monthMoney=  monthMoney.add(monthCount.get(i));
        }
        //查询当年订单总数
        List<BigDecimal> yearCount= this.baseMapper.getYearCount(params);
        for (int i=0;i<yearCount.size();i++){
            yearMoney=  yearMoney.add(yearCount.get(i));
        }
        Map<String,Object> totalCount=new HashMap<>();
        totalCount.put("dayCount",dayCount.size());
        totalCount.put("monthCount",monthCount.size());
        totalCount.put("yearCount",yearCount.size());
        totalCount.put("dayMoney",dayMoney.setScale(2,BigDecimal.ROUND_HALF_UP));
        totalCount.put("monthMoney",monthMoney.setScale(2,BigDecimal.ROUND_HALF_UP));
        totalCount.put("yearMoney",yearMoney.setScale(2,BigDecimal.ROUND_HALF_UP));
        return R.ok().put("page",pageUtils).put("productionStatusEnum",JsonUtils.enumToList(ProductionStatusEnum.class))
                .put("payStatusEnum",JsonUtils.enumToList(PayStatusEnum.class))
                .put("orderSourceEnum",JsonUtils.enumToList(OrderSourceEnum.class))
                .put("totalCount",totalCount);
    }

    /**
     * 根据产品名称查询商品列表，查询十条
     * @param params
     * @return
     */
    @Override
    public R querySearchProduct(Map<String, Object> params) {
        List<GoodsInfoVo>  productData=  goodsService.querySearchProduct(params);
        //组装value字段数据
        for (int i=0;i<productData.size();i++){
            GoodsInfoVo goodsInfoVo = productData.get(i);
            StringBuilder sb=new StringBuilder();
            sb.append(goodsInfoVo.getName()).append("(").append(goodsInfoVo.getProductInfo()).append(")");
            goodsInfoVo.setValue(sb.toString());
        }
        return R.ok().put("productData",productData);
    }

    @Override
    public R addData(Long sellerId,String username) {
        List<SysUserEntity> acceptOrderUserData =sysUserService.getAcceptOrderUserlist(sellerId);
        // 查询省市区级联数据
        List<String> area =this.queryRegionsSascade();
        return R.ok().put("acceptOrderUserData",acceptOrderUserData)
                     .put("currentUser",username)
                     .put("area",JSONArray.fromObject(area).toString());
    }

    //图文宝查询会员信息，还有账套信息
    @Override
    public R searchMember(Map<String, Object> params) {
        return storeMemberService.getMemberByName(params);
    }


    //图文宝添加订单
    @Override
    @Transactional(rollbackFor =Exception.class)
    public R saveTwbOrder(ErpOrderItemDto erpOrderItemDto) {
        List<ErpOrderItemEntity> erpOrderItemEntityList= erpOrderItemDto.getErpOrderItemList();
        if(erpOrderItemEntityList.size()==0){
            return R.error("商品明细不能为空!");
        }
        ErpOrderEntity erpOrder = erpOrderItemDto.getErpOrder();
        Integer sellerId=erpOrder.getThirdMerchantId();
        // 订单号生成
        String orderNo = "";
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyMMddHHmm");
        boolean flag = true;
        do {
            orderNo = "5"+ dateFormat.format(new Date()) + (int) (Math.random() * 90 + 10)+(int) (Math.random() * 90 + 10);
            // 判断订单号是否已存在
            ErpOrderEntity checkOrder = this.getById(orderNo);
            if (checkOrder == null || checkOrder.getOrderNo() == null) {
                flag = false;
            }
        } while (flag);
        erpOrder.setOrderNo(orderNo);
        erpOrder.setOriginalOrderId(Long.valueOf(orderNo));
        erpOrder.setShipStatus(ShipStatusEnum.NOT_SHIPPED.toInt());
        erpOrder.setReceivedStatus(ReceivedStatusEnum.UN_RECEIVED.toInt());
        //计算 总金额
        BigDecimal totalMoney = erpOrderItemEntityList.stream().map(ErpOrderItemEntity::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
        erpOrder.setTotalAmount(totalMoney);
        //再查询会员信息，看是否有优惠
        //先查看前台是否传递sid,如果没传则需要新增会员
        Long storeMemberId= erpOrder.getStoreMemberId();
        //查询storeMember表是否存在此客户
        //如果当前客户不在storeMember
        if (null == storeMemberId) {
            StoreMemberEntity storeMember=new StoreMemberEntity();
            //添加数据到storeMember
            storeMember.setSellerId(sellerId);
            storeMember.setMerchantsType(MerchantsTypeEnum.VISIT.toCode());
            storeMember.setMerchantsSalesMan(erpOrder.getMerchantsSalesMan());
            storeMember.setAddr(erpOrder.getShipAddr());
            storeMember.setMobile(erpOrder.getShipMobile());
            storeMember.setTel(erpOrder.getShipTel());
            storeMember.setName(erpOrder.getMemberName());
            storeMember.setHangsAccountCustomer(0);
            storeMember.setMemberId(0);//写死.默认为0
            storeMember.setAutoClear(0);
            storeMember.setCreateTime(new Date());
            storeMember.setNickname(erpOrder.getShipName());
            storeMember.setMerchantsSource(1);
            storeMemberService.save(storeMember);
            erpOrder.setMemberId(0);
            erpOrder.setStoreMemberId(storeMember.getSid());
        }
        Map<String,Object> params=new HashMap<>();
        params.put("sellerId",sellerId);
        params.put("sid",erpOrder.getStoreMemberId());
        StoreMemberEntityVo storeMemberEntity= storeMemberService.getMemberBySId(params);
        //会员折扣率
        BigDecimal discountRate = storeMemberEntity.getDiscountRate();
        if(discountRate==null){
            erpOrder.setPayableAmount(totalMoney);
            erpOrder.setPmtGoods(new BigDecimal(0));
        }else{
            BigDecimal payableAmount=totalMoney.multiply(discountRate).setScale(2,BigDecimal.ROUND_HALF_UP);
            BigDecimal pmtGoods=totalMoney.subtract(payableAmount);
            erpOrder.setPmtGoods(pmtGoods);
            erpOrder.setPayableAmount(payableAmount);
        }
        //是否有押金，如果有押金，则需要生成支付信息
        //配送费用
        erpOrder.setCostFreight(new BigDecimal(0));
        //true为收取押金
        if (erpOrder.getDeposit()) {
            //收取押金则还需要在user_payment表中生成一条数据
            /* 新增用户支付记录表信息 */
            String paymentsId = UserPaymentUtils.getPaymentsId();
            // 防重复支付单号
            boolean repeat = true;
            do {
                UserPaymentEntity upe = userPaymentService.getById(paymentsId);
                if (upe == null) {
                    repeat = false;
                }
            } while (repeat);
            UserPaymentEntity userPayment = new UserPaymentEntity();
            userPayment.setPaymentId(paymentsId);
            erpOrder.setPaymentId(userPayment.getPaymentId());
            userPayment.setUserId(erpOrder.getMemberId().toString());
            userPayment.setStatus(UserPaymentStatusEnum.SUCC.toCode());
            userPayment.setCurMoney(erpOrder.getPayed());
            userPayment.setOpId(sellerId.toString());
            userPayment.setMoney(erpOrder.getPayed());
            //押金
            userPayment.setPayType(PayTypeWayEnum.PAY_DEPOSIT.toCode());
            /*userPayment.setPayAppId(EnumUtil.getEnumByDesc(PayTypeEnum.class, erpOrder.getPayment()).toCode());*/
            userPayment.setTPayed(new Date());
            userPaymentService.save(userPayment);

            /* 新增用户支付关联表信息 */
            UserPaymentBillEntity userPaymentBill = new UserPaymentBillEntity();
            userPaymentBill.setRelId(Long.valueOf(erpOrder.getOrderNo()));
            userPaymentBill.setBillType(BillTypeEnum.PAYMENTS.toCode());
            userPaymentBill.setPayObject(PayObjectEnum.ORDER_FOREGIFT.toCode());
            userPaymentBill.setBillId(userPayment.getPaymentId());
            userPaymentBill.setMoney(userPayment.getMoney());
            userPaymentBillService.save(userPaymentBill);
        }
        //未支付
        erpOrder.setPayStatus(PayStatusEnum.NOT_PAY_0.toInt());
        //前台传入这个主要是用于计算押金，生成支付单后，要将这个清0
        erpOrder.setPayed(BigDecimal.ZERO);
        //查询当前用户是否为自营的，为将third_merchant_type设置为1
        SellerInfoEntity sellerInfoEntity = sellerInfoService.getById(sellerId);
        if(sellerInfoEntity.getSelf()==1){
            erpOrder.setThirdMerchantType(1);
        }else{
            //如果商户类型为小B
            if(sellerInfoEntity.getSellerType().equals("0")){
                erpOrder.setThirdMerchantType(2);
            }
            //如果商户类型为工厂
            if(sellerInfoEntity.getSellerType().equals("1")){
                erpOrder.setThirdMerchantType(3);
            }
        }
        erpOrder.setSource("erp");
        //1为普通订单
        erpOrder.setOrderType(OrderTypeEnum.GENERAL.toInt());
        erpOrder.setDel(false);
        //订单创建时间
        erpOrder.setCreateTime(new Date());
        erpOrder.setOrderSource(OrderSourceEnum.OFFlINE.toInt());
        //图文宝开单直接就是生产中
        erpOrder.setProductionStatus(ProductionStatusEnum.IN_PRODUCTION.toInt());
        erpOrder.setThirdMerchantId(sellerId.intValue());
        this.save(erpOrder);

        for (int i=0;i<erpOrderItemEntityList.size();i++){
            ErpOrderItemEntity erpOrderItemEntity = erpOrderItemEntityList.get(i);
            erpOrderItemEntity.setOrderNo(orderNo);
        }
        if(erpOrderItemEntityList.size()>0){
            erpOrderItemService.saveBatch(erpOrderItemEntityList);
        }
        //添加新开单日志
        ErpOrderLogEntity erpOrderLogEntity = new ErpOrderLogEntity();
        erpOrderLogEntity.setLogText("图本宝新开单，生产状态为生产中");
        erpOrderLogEntity.setOrderNo(erpOrder.getOrderNo());
        erpOrderLogEntity.setCreateTime(new Date());
        erpOrderLogEntity.setCreateName(UserUtils.getCurentUser().getUsername());
        erpOrderLogService.save(erpOrderLogEntity);
        return R.ok();
    }

    @Override
    public R twbOrderInfo(String orderNo) {
        R re = R.ok();
        // 订单信息
        ErpOrderEntity erpOrder =  this.getById(orderNo);
        //处理数据用于前台展示
        re.put("erpOrder", erpOrder);
            if(erpOrder.getDeposit()!=null&&erpOrder.getDeposit()==true){
            //通过支付单号查询押金
            String paymentId = erpOrder.getPaymentId();
            if(StringUtils.isNotBlank(paymentId)){
                UserPaymentEntity userPaymentEntity = userPaymentService.getOne(new QueryWrapper<UserPaymentEntity>().eq("payment_id", paymentId).eq("pay_type", PayTypeWayEnum.PAY_DEPOSIT.toCode()));
                if(userPaymentEntity!=null){
                    erpOrder.setDepositMoney(userPaymentEntity.getCurMoney());
                }else {
                    erpOrder.setDepositMoney(BigDecimal.ZERO);
                }
            }
        }

        // 商品列表
        List<ErpOrderItemEntity> orderItemDetailData = erpOrderItemService.list(
                new QueryWrapper<ErpOrderItemEntity>()
                        .eq("order_no",orderNo)
                        .eq("item_del",0)
        );
        //先根据订单中的storeMemberId查询客户账号以及折扣率
        Long storeMemberId = erpOrder.getStoreMemberId();
        Map<String,Object> param=new HashMap<>();
        param.put("sid",storeMemberId);
        param.put("sellerId",UserUtils.getCurentUser().getSellerId());
        StoreMemberEntityVo memberBySId = storeMemberService.getMemberBySId(param);

        //回显优惠金额
        if(memberBySId!=null){
            if(memberBySId.getDiscountRate()!=null){
                BigDecimal discount=new BigDecimal(1).subtract(memberBySId.getDiscountRate());
                for (int i=0;i<orderItemDetailData.size();i++){
                    ErpOrderItemEntity erpOrderItemEntity = orderItemDetailData.get(i);
                    erpOrderItemEntity.setPmtGoods(erpOrderItemEntity.getAmount().multiply(discount).setScale(2,BigDecimal.ROUND_HALF_UP));
                }
            }
        }
        re.put("orderItemDetailData", orderItemDetailData);

        // 已分配列表
        Map<String, Object> params = new HashMap<>();
        params.put("orderNo", orderNo);
        params.put("del", DeleteEnum.NOT_DELETE.toInt());
        List<ErpOrderProductionListVo> erpOrderProductionList = erpOrderProductionService.queryTwbProductionList(params);
        re.put("erpOrderProductionList", erpOrderProductionList);
        return re;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R batchAudit(String auditName, String orderNos,String createBy) {
        Map<String,Object> map=new HashMap<>();
        String[] split = orderNos.split(",");
        List<String> idList=new ArrayList<>();
        for (int i=0;i<split.length;i++){
            idList.add(split[i]);
        }
        List<ErpOrderEntity> erpOrderEntities = (List<ErpOrderEntity>) this.listByIds(idList);
        //定义一个集合获取所有订单号
        List<String> orderNoList=new ArrayList<>();
        //判断是否所有订单状态是否均为待审核
        for (int i=0;i<erpOrderEntities.size();i++){
            ErpOrderEntity erpOrderEntity=erpOrderEntities.get(i);
           String orderNo= erpOrderEntity.getOrderNo();
            orderNoList.add(orderNo);
            if(erpOrderEntity.getProductionStatus()!=ProductionStatusEnum.UN_AUDITED.toInt()){
                return R.error("请检查所选订单生产状态是否均为<span style='color: red;'>待审核</span>状态!只有待审核才能进行审核操作");
            }
            //查询是否是自营分配的，这类订单无支付信息
            Boolean ziyunAllot = this.isZiyunAllot(orderNo);
            //未支付订单。且不属于自营分配，不允许审核
            if(!erpOrderEntity.getPayStatus().toString().equals(PayStatusEnum.ALREADY_PAY_1.toCode())&&!ziyunAllot){
                return R.error("请先确认订单<span style='color: red;'>"+orderNo+"</span>是否已经支付!未支付订单不允许进行审核操作!");
            }
        }
        map.put("auditName",auditName);
        map.put("auditTime",new Date());
        map.put("productionStatus",ProductionStatusEnum.IN_PRODUCTION.toInt());
        this.baseMapper.batchUpdate(map, idList);
        //先获取所有订单号,如果是分配过来的，需要将生产单状态改为生产中
       List<ErpOrderProductionEntity> productionList=  erpOrderProductionService.selectProductionListByOrderNos(orderNoList);
       for (int i=0;i<productionList.size();i++){
           productionList.get(i).setProductionStatus(2); //1.待生产,2.生产中,3.生产完成,4.取消
       }
       if(productionList.size()>0){
           erpOrderProductionService.updateBatchById(productionList);
       }
        //添加订单日志
        List<ErpOrderLogEntity> orderLogEntityList=new ArrayList<>();
        for (int i = 0; i <idList.size(); i++) {
            String orderNo = idList.get(i);
            ErpOrderLogEntity erpOrderLogEntity=new ErpOrderLogEntity();
            erpOrderLogEntity.setOrderNo(orderNo);
            erpOrderLogEntity.setCreateBy(createBy);
            erpOrderLogEntity.setCreateName(auditName);
            erpOrderLogEntity.setCreateTime(new Date());
            erpOrderLogEntity.setLogText("批量审核操作");
            orderLogEntityList.add(erpOrderLogEntity);
        }
        if(orderLogEntityList.size()>0){
            erpOrderLogService.saveBatch(orderLogEntityList);
        }
        return R.ok();
    }


    /**
     * 图文宝订单生产完成
     * @param createName
     * @param orderNos
     * @param createBy
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R finishTwbOrder(String createName, String orderNos, String createBy) {
        String[] split = orderNos.split(",");
        List<String> idList=new ArrayList<>();
        for (int i=0;i<split.length;i++){
            idList.add(split[i]);
        }
        List<ErpOrderEntity> erpOrderEntities = (List<ErpOrderEntity>) this.listByIds(idList);
        //判断是否所有订单状态是否均为生产中
        for (int i=0;i<erpOrderEntities.size();i++) {
            ErpOrderEntity erpOrderEntity = erpOrderEntities.get(i);
            String orderNo=erpOrderEntity.getOrderNo();
            if(erpOrderEntity.getProductionStatus()!=ProductionStatusEnum.IN_PRODUCTION.toInt()){
                return R.error("请检查所选订单生产状态是否均为<span style='color: red;'>生产中</span>状态!只有<span style='color: red;'>生产中</span>订单才能进行订单完成操作!");
            }
            //查询是否是自营分配的，这类订单无支付信息
            Boolean ziyunAllot = this.isZiyunAllot(orderNo);
            //如果是商城订单，并且不是自营分配的，未支付订单不允许进行生产完成操作
            if(!erpOrderEntity.getPayStatus().toString().equals(PayStatusEnum.ALREADY_PAY_1.toCode())&&erpOrderEntity.getOrderSource()==OrderSourceEnum.ZIYUN.toInt()&&!ziyunAllot){
                return R.error("请先确认订单<span style='color: red;'>"+orderNo+"</span>是否已经支付!未支付订单不允许进行生产完成操作!");
            }
            //查询支付表，如果没有支付成功信息，也提示不允许进行操作！
             if(erpOrderEntity.getOrderSource()==OrderSourceEnum.ZIYUN.toInt()){
                      //如果不是自营分配，再查询支付信息
                      if(!ziyunAllot){
                          UserPaymentEntity userPayment = userPaymentService.getPaySuccLastEntityByOrderId(erpOrderEntity.getOrderNo());
                          if(userPayment==null){
                              return R.error("请先确认订单<span style='color: red;'>"+erpOrderEntity.getOrderNo()+"</span>是否已经支付!未支付订单不允许进行生产完成操作!");
                          }
                  }
            }
            //首先判断是否为分配过来订单
            int count = erpOrderAllotRelevanceService.count(new QueryWrapper<ErpOrderAllotRelevanceEntity>().eq("order_allot_no", erpOrderEntity.getOrderNo())
                    .eq("del", DeleteEnum.NOT_DELETE.toInt()));
            //如果是分配过来订单，并且是自提，则改变发货状态，生产状态为生产完成
            erpOrderEntity.setFinishTime(new Date());
            if(erpOrderEntity.getOrderSource()==OrderSourceEnum.ZIYUN.toInt()&&erpOrderEntity.getSendType()==SendTypeEnum.PICK_UP.toInt()&&count>0){
                erpOrderEntity.setProductionStatus(ProductionStatusEnum.PRODUCTION_FINISH.toInt());
                erpOrderEntity.setShipStatus(Integer.valueOf(ShipStatusEnum.shipped.toCode()));
            }else if(erpOrderEntity.getOrderSource()==OrderSourceEnum.ZIYUN.toInt()&&erpOrderEntity.getSendType()==SendTypeEnum.PICK_UP.toInt()&&count==0){
                //如果是本身商城下的订单，并且是自提，生产完成就是已完成并发货
                erpOrderEntity.setProductionStatus(ProductionStatusEnum.FINISH.toInt());
                erpOrderEntity.setShipStatus(Integer.valueOf(ShipStatusEnum.shipped.toCode()));
                erpOrderEntity.setReceivedStatus(ReceivedStatusEnum.RECEIVED.toInt());
                erpOrderEntity.setReceivedTime(new Date());
                erpOrderEntity.setSendTime(new Date());
                erpOrderEntity.setDeliveryTime(new Date());
            }else{
                erpOrderEntity.setProductionStatus(ProductionStatusEnum.PRODUCTION_FINISH.toInt());
            }
        }
        //批量更改状态，erpOrder
        this.updateBatchById(erpOrderEntities);
        //根据订单号去order_info表中查询，查询出来的均为商城订单或者分配过来订单
        List<OrderInfoEntity> orderInfoList = (List<OrderInfoEntity>) orderInfoService.listByIds(idList);
        //定义一个集合，用于修改orderInfo表中信息
        List<OrderInfoEntity> updateOrderInfoList=new ArrayList<>();
        //定义一个集合，用于修改erp_order_production表中信息
        List<ErpOrderProductionEntity> erpOrderProductionEntityList=new ArrayList<>();
        for (int i=0;i<orderInfoList.size();i++){
            OrderInfoEntity orderInfoEntity = orderInfoList.get(i);
            //首先判断是否为分配过来订单
            int count = erpOrderAllotRelevanceService.count(new QueryWrapper<ErpOrderAllotRelevanceEntity>().eq("order_allot_no", orderInfoEntity.getOrderId())
                    .eq("del", DeleteEnum.NOT_DELETE.toInt()));
            //如果不是分配，并且自提，
            if(orderInfoEntity.getPickUp()&&!orderInfoEntity.getSource().equals("erp")&&count==0){
                orderInfoEntity.setStatus(OrderInfoStatusEnum.FINISH.toCode());
                orderInfoEntity.setShipStatus(ShipStatusEnum.shipped.toCode());
                orderInfoEntity.setReceivedStatus(true);
                orderInfoEntity.setReceivedTime(new Date());
                orderInfoEntity.setShipTime("自取");
                updateOrderInfoList.add(orderInfoEntity);
                continue;
            }
            //如果不是分配,非自提,不修改orderInfo信息
            if(!orderInfoEntity.getPickUp()&&(!orderInfoEntity.getSource().equals("erp"))&&count==0){
                continue;
            }
            //如果是分配,自提,只更改发货状态和生产状态
            if(orderInfoEntity.getPickUp()&&(!orderInfoEntity.getSource().equals("erp"))&&count>0){
                orderInfoEntity.setShipStatus(ShipStatusEnum.shipped.toCode());
                updateOrderInfoList.add(orderInfoEntity);
                //查询生产单信息
                List<ErpOrderProductionEntity> productionList = erpOrderProductionService.list(new QueryWrapper<ErpOrderProductionEntity>().eq("production_order", orderInfoEntity.getOrderId())
                        .notIn("production_status", OrderProductionStatusEnum.CANCLE.toInt()).eq("del", 0));
                for (int j=0;j<productionList.size();j++){
                    ErpOrderProductionEntity erpOrderProductionEntity = productionList.get(j);
                    erpOrderProductionEntity.setProductionStatus(3); //1.待生产,2.生产中,3.生产完成,4.取消
                    erpOrderProductionEntityList.add(erpOrderProductionEntity);
                }
                continue;
            }
            //如果是分配，不自提,只修改生产单信息
            if(!orderInfoEntity.getPickUp()&&(!orderInfoEntity.getSource().equals("erp"))&&count>0){
                //查询生产单信息
                List<ErpOrderProductionEntity> productionList = erpOrderProductionService.list(new QueryWrapper<ErpOrderProductionEntity>().eq("production_order", orderInfoEntity.getOrderId())
                        .eq("production_status", OrderProductionStatusEnum.CANCLE.toInt()).eq("del", 0));
                for (int j=0;j<productionList.size();j++){
                    ErpOrderProductionEntity erpOrderProductionEntity = productionList.get(j);
                    erpOrderProductionEntity.setProductionStatus(3); //1.待生产,2.生产中,3.生产完成,4.取消
                    erpOrderProductionEntityList.add(erpOrderProductionEntity);
                }
            }
        }
        if(updateOrderInfoList.size()>0){
            orderInfoService.updateBatchById(updateOrderInfoList);
        }
        if(erpOrderProductionEntityList.size()>0){
            erpOrderProductionService.updateBatchById(erpOrderProductionEntityList);
        }
        //添加订单日志
        List<ErpOrderLogEntity> orderLogEntityList=new ArrayList<>();
        for (int i = 0; i <idList.size(); i++) {
            String orderNo = idList.get(i);
            ErpOrderLogEntity erpOrderLogEntity=new ErpOrderLogEntity();
            erpOrderLogEntity.setOrderNo(orderNo);
            erpOrderLogEntity.setCreateBy(createBy);
            erpOrderLogEntity.setCreateName(createName);
            erpOrderLogEntity.setCreateTime(new Date());
            erpOrderLogEntity.setLogText("批量生产完成操作");
            orderLogEntityList.add(erpOrderLogEntity);
        }
        if(orderLogEntityList.size()>0){
            erpOrderLogService.saveBatch(orderLogEntityList);
        }
        return R.ok();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R cancelTwbOrder(ErpOrderLogEntity erpOrderLogs) {
        //先根据订单号判断订单的生产状态
        ErpOrderEntity erpOrderEntity = this.baseMapper.selectOne(new QueryWrapper<ErpOrderEntity>().eq("order_no", erpOrderLogs.getOrderNo()));
        //先判断，如果商城订单不允许进行取消操作
        if(erpOrderEntity.getOrderSource()==OrderSourceEnum.ZIYUN.toInt()){
            return R.error("商城订单不允许进行<span style='color: red;'>取消订单</span>操作!");
        }
        if (erpOrderEntity.getProductionStatus() != ProductionStatusEnum.IN_PRODUCTION.toInt()) {
            return R.error("只有生产状态为<span style='color: red;'>生产中</span>订单才能取消!");
        } else {
            //将订单状态变为已作废
            erpOrderEntity.setProductionStatus(ProductionStatusEnum.CANCELLED.toInt());
            this.baseMapper.updateById(erpOrderEntity);
            //先查询当前订单下的所有订单商品
            List<ErpOrderItemEntity> erpOrderItemEntityList = erpOrderItemService.selectListByErpOrder(erpOrderLogs.getOrderNo());
            for (int i = 0; i < erpOrderItemEntityList.size(); i++) {
                erpOrderItemEntityList.get(i).setItemDel(1);
            }
            //删除商品详情表
            if (erpOrderItemEntityList.size() > 0) {
                erpOrderItemService.updateBatchById(erpOrderItemEntityList);
            }
            erpOrderLogService.save(erpOrderLogs);
            //再查询外协订单，进行删除
            List<ErpOrderProductionEntity> erpOrderProductionEntities = erpOrderProductionService.list(new QueryWrapper<ErpOrderProductionEntity>().eq("order_no", erpOrderEntity.getOrderNo()).eq("del", DeleteEnum.NOT_DELETE.toInt()));
            for (int i=0;i<erpOrderProductionEntities.size();i++){
                ErpOrderProductionEntity erpOrderProductionEntity = erpOrderProductionEntities.get(i);
                erpOrderProductionEntity.setProductionStatus(4); //4.取消
                erpOrderProductionEntity.setDel(DeleteEnum.DELETE.toInt());
            }
            if(erpOrderProductionEntities.size()>0){
                erpOrderProductionService.updateBatchById(erpOrderProductionEntities);
            }
        }
        return R.ok();
    }

    @Override
    public R getTwbReceviceMoneyData(String orderNo) {
        //查询订单总额等相关信息
        ErpOrderEntity erpOrder=this.getById(orderNo);
        if(erpOrder.getOrderSource()!=OrderSourceEnum.OFFlINE.toInt()){
            return  R.error("只有<span style='color: red;'>门市</span>订单可以进行收银操作!");
        }
        if(erpOrder.getProductionStatus()!=ProductionStatusEnum.PRODUCTION_FINISH.toInt()){
            return  R.error("只有<span style='color: red;'>生产完成</span>订单可以进行收银操作!");
        }

        if(erpOrder.getPayStatus().toString()==PayStatusEnum.ALREADY_PAY_1.toCode()){
            return  R.error("已支付订单无需进行收银操作!");
        }
        Long storeMemberId = erpOrder.getStoreMemberId();
        //根据storeMemberId查询客户是否为挂账客户
        StoreMemberEntity storeMemberEntity = storeMemberService.getById(storeMemberId);
        // 应付金额
        BigDecimal payableAmount = erpOrder.getPayableAmount();
        BigDecimal payed = erpOrder.getPayed() == null ? BigDecimal.ZERO : erpOrder.getPayed();
        BigDecimal money = payableAmount;
        BigDecimal pmtGoods=erpOrder.getPmtGoods()==null?BigDecimal.ZERO : erpOrder.getPmtGoods();
        // 将数据重新封装传给前台
        Map<String,Object> recMoney=new HashMap<>();
        recMoney.put("orderNo",erpOrder.getOrderNo());
        recMoney.put("memberName",erpOrder.getMemberName());
        recMoney.put("totalMount",erpOrder.getTotalAmount());
        recMoney.put("pmtGoods",pmtGoods);
        recMoney.put("discount",erpOrder.getDiscount());
        recMoney.put("payableAmount",money);
        recMoney.put("memberId",erpOrder.getMemberId());
        recMoney.put("money",money);
        recMoney.put("payed",payed);
        recMoney.put("payName","现金");//默认现金收银
        recMoney.put("onCredit", storeMemberEntity.getHangsAccountCustomer()==1);
        //判断如果订单为收取押金，则押金金额=已支付金额
        if(erpOrder.getDeposit()){
            //通过支付单号查询押金
            String paymentId = erpOrder.getPaymentId();
            if(StringUtils.isNotBlank(paymentId)){
                UserPaymentEntity userPaymentEntity = userPaymentService.getOne(new QueryWrapper<UserPaymentEntity>().eq("payment_id", paymentId).eq("pay_type", PayTypeWayEnum.PAY_DEPOSIT.toCode()));
                if(userPaymentEntity!=null){
                    recMoney.put("depositMoney",userPaymentEntity.getCurMoney());
                }else {
                    recMoney.put("depositMoney",BigDecimal.ZERO);
                }
            }
        }else{
            recMoney.put("depositMoney",BigDecimal.ZERO );
        }
        return R.ok().put("payTypeEnum",JsonUtils.enumToList(TwbPayTypeEnum.class))
                .put("recMoney",recMoney);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R saveTwbReceviceMoneyData(Map<String, Object> params) {
        String payName = params.get("payName").toString();
        String memberId = params.get("memberId").toString();
        BigDecimal money = new BigDecimal(params.get("money").toString());
        Boolean onCredit =Boolean.valueOf(params.get("onCredit").toString()) ;
        String orderNo = params.get("orderNo").toString();
        if (!StringUtils.isNotBlank(payName)) {
            return R.error("获取支付方式失败，收银失败!");
        }
        if (!StringUtils.isNotBlank(orderNo)) {
            return R.error("获取订单相关数据错误，收银失败!");
        }
        //收款成功后，更改订单状态为已完结,已支付
        ErpOrderEntity erpOrder = this.getById(orderNo);
        erpOrder.setOnCredit(onCredit);
        //先判断订单状态是否为生产完成
        if(erpOrder.getProductionStatus()!=ProductionStatusEnum.PRODUCTION_FINISH.toInt()){
            return  R.error("当前订单状态不是<span style='color: red;'>生产完成</span>，无法进行收银操作!");
        }
        //先判断订单状态是否为已完结
        if(erpOrder.getProductionStatus()==ProductionStatusEnum.FINISH.toInt()){
            return  R.error("当前订单已完结，请刷新页面查看订单最新状态!");
        }
        //判断订单是否为门店订单，不是，则不允许进行收款操作
        if(erpOrder.getOrderSource()!=OrderSourceEnum.OFFlINE.toInt()){
            return R.error("非<span style='color: red;'>门店</span>订单不允许进行收银操作!");
        }
        //先判断是否是收取押金订单，如果是，则需要添加一条为负的订单流水
        if(erpOrder.getDeposit()){
            //根据订单号查询押金流水
            UserPaymentBillEntity userPaymentBillEntity = userPaymentBillService.getById(erpOrder.getOrderNo());
            if(userPaymentBillEntity!=null){
                //先得到要退还金额
                BigDecimal returnMoney=BigDecimal.ZERO.subtract(userPaymentBillEntity.getMoney());
                //添加支付单信息
                UserPaymentEntity userPayment = new UserPaymentEntity();
                // 收款单号
                String paymentId = UserPaymentUtils.getPaymentsId();
                // 判断收款单号是否重复
                boolean repeat = true;
                do {
                    List<UserPaymentEntity> countList = userPaymentService.list(new QueryWrapper<UserPaymentEntity>().eq("payment_id", paymentId));
                    if (countList == null || countList.size() <= 0) {
                        repeat = false;
                    }
                } while (repeat);
                userPayment.setPaymentId(paymentId);
                userPayment.setMoney(returnMoney);
                userPayment.setCurMoney(returnMoney);
                userPayment.setUserId(memberId);
                userPayment.setStatus("succ");
                userPayment.setPayName(payName);
                userPayment.setTPayed(new Date());
                userPayment.setPayType("offline");//线下支付
                userPayment.setPayAppId(EnumUtil.getEnumByDesc(PayTypeEnum.class, payName).toCode());
                //用户支付记录表;
                userPaymentService.save(userPayment);

                // 订单，支付单关联信息
                UserPaymentBillEntity userPaymentBill = new UserPaymentBillEntity();
                userPaymentBill.setRelId(Long.valueOf(orderNo));
                userPaymentBill.setBillId(userPayment.getPaymentId());
                userPaymentBill.setPayObject(PayObjectEnum.ORDER.toCode());
                userPaymentBill.setBillType(BillTypeEnum.REFUNDS.toCode());
                userPaymentBill.setMoney(userPayment.getMoney());
                userPaymentBillService.save(userPaymentBill);
            }
        }

        //添加支付单信息
        UserPaymentEntity userPayment = new UserPaymentEntity();
        // 收款单号
        String paymentId = UserPaymentUtils.getPaymentsId();
        // 判断收款单号是否重复
        boolean repeat = true;
        do {
            List<UserPaymentEntity> countList = userPaymentService.list(new QueryWrapper<UserPaymentEntity>().eq("payment_id", paymentId));
            if (countList == null || countList.size() <= 0) {
                repeat = false;
            }
        } while (repeat);
        userPayment.setPaymentId(paymentId);
        userPayment.setMoney(money);
        userPayment.setCurMoney(money);
        userPayment.setUserId(memberId);
        userPayment.setStatus("succ");
        userPayment.setPayName(payName);
        userPayment.setTPayed(new Date());
        userPayment.setPayType("offline");//线下支付
        userPayment.setPayAppId(EnumUtil.getEnumByDesc(PayTypeEnum.class, payName).toCode());
        //用户支付记录表;
        userPaymentService.save(userPayment);
        // 订单，支付单关联信息
        UserPaymentBillEntity userPaymentBill = new UserPaymentBillEntity();
        userPaymentBill.setRelId(Long.valueOf(orderNo));
        userPaymentBill.setBillId(userPayment.getPaymentId());
        userPaymentBill.setPayObject(PayObjectEnum.ORDER.toCode());
        userPaymentBill.setBillType(BillTypeEnum.PAYMENTS.toCode());
        userPaymentBill.setMoney(userPayment.getMoney());
        userPaymentBillService.save(userPaymentBill);


        //创建erp_order_log
        ErpOrderLogEntity erpOrderLog = new ErpOrderLogEntity();
        erpOrderLog.setOrderNo(orderNo);
        erpOrderLog.setCreateName(UserUtils.getCurentUser().getUsername());
        erpOrderLog.setCreateTime(new Date());
        erpOrderLog.setCreateBy(UserUtils.getCurentUser().getSellerId().toString());
        erpOrderLog.setLogText("订单收款，金额:"+money+"元");
        erpOrderLogService.save(erpOrderLog);

        //判断是否为自提，如果为自提，则收银结算将发货状态和收货状态更改为已收货
        if (erpOrder.getSendType() == SendTypeEnum.PICK_UP.toInt()) {
            //1为已发货
            erpOrder.setShipStatus(1);
            erpOrder.setReceivedStatus(ReceivedStatusEnum.RECEIVED.toInt());
            erpOrder.setReceivedTime(new Date());
        }
        // 修改已支付金额
        BigDecimal payed = money;
        // 抹零金额添加至调价
        BigDecimal discount = erpOrder.getDiscount();
        BigDecimal payableAmount = erpOrder.getPayableAmount();
        BigDecimal subtract = payed.subtract(payableAmount);
        discount = subtract.add(discount);
        erpOrder.setDiscount(discount);
        erpOrder.setPayableAmount(payed);
        erpOrder.setPayed(payed);
        erpOrder.setPayment(payName);
        erpOrder.setPayStatus(Integer.valueOf(PayStatusEnum.ALREADY_PAY_1.toCode()));
        erpOrder.setProductionStatus(ProductionStatusEnum.FINISH.toInt());
        erpOrder.setPaymentTime(new Date());
        erpOrder.setPaymentId(userPayment.getPaymentId());
        erpOrder.setLastModifiedTime(new Date());
        erpOrder.setIsUrgent(0);
        this.updateById(erpOrder);
        return  R.ok();
    }

    /**
     * 图文宝添加物流前查询所需要的信息
     * @param orderNo
     * @return
     */
    @Override
    public R twbLogisticInfo(String orderNo,Long sellerId) {
        // 订单信息
        ErpOrderEntity erpOrder = this.getById(orderNo);
        // 查询订单区域路径
        String regionPath = null;
        Integer shipAreaId = erpOrder.getShipAreaId();
        if (shipAreaId != null){
            SdbEctoolsRegionsEntity sdbEctoolsRegionsEntity = sdbEctoolsRegionsService.getById(shipAreaId);
            regionPath = sdbEctoolsRegionsEntity.getRegionPath();
        }
        // 商品详情
        List<ErpOrderItemEntity> erpOrderItemEntityList = erpOrderItemService.list(new QueryWrapper<ErpOrderItemEntity>().eq("order_no",orderNo));
        // 省市区级联数据
        List<String> area = this.queryRegionsSascade();
        // 物流类型
        List<Map<Integer,String>> logisticsTypeList = logisticsTypeService.queryTypeList();
        return R.ok().put("orderInfo", erpOrder)
                .put("erpOrderItemEntityList", erpOrderItemEntityList)
                .put("area", JSONArray.fromObject(area).toString())
                .put("logisticsTypeList", logisticsTypeList)
                .put("regionPath", regionPath);
    }


    /**
     * 图文宝订单修改前查询订单信息
     * @param
     * @param
     * @return
     */
    @Override
    public R twbUpdateOrderInfo(String orderNo) {
        //查询订单信息
        ErpOrderEntity erpOrderEntity = this.getById(orderNo);
        if(erpOrderEntity.getOrderSource()==OrderSourceEnum.ZIYUN.toInt()){
            return R.error("商城订单不允许进行修改操作!");
        }
        //判断订单状态。只有新开单和生产中订单允许修改
        if(erpOrderEntity.getProductionStatus()!=ProductionStatusEnum.NEW_ORDER.toInt()
                &&erpOrderEntity.getProductionStatus()!=ProductionStatusEnum.IN_PRODUCTION.toInt()){
            return R.error("只允许生产状态为<span style='color: red;'>生产中</span>的订单进行修改操作!");
        }
        Integer sellerId = erpOrderEntity.getThirdMerchantId();
        List<SysUserEntity> acceptOrderUserData =sysUserService.getAcceptOrderUserlist(sellerId.longValue());
        // 商品列表
        List<ErpOrderItemEntity> erpOrderItemData = erpOrderItemService.list(
                new QueryWrapper<ErpOrderItemEntity>()
                        .eq("order_no",orderNo)
                        .eq("item_del",0)
        );
        // 查询省市区级联数据
        List<String> area =this.queryRegionsSascade();
        return R.ok().put("acceptOrderUserData",acceptOrderUserData)
                .put("currentUser",erpOrderEntity.getAcceptOrderUser())
                .put("area",JSONArray.fromObject(area).toString())
                .put("erpOrderItemData", erpOrderItemData)
                .put("erpOrder",erpOrderEntity);
    }

    /**
     * 图文宝订单修改
     * @param erpOrderItemDto
     * @return
     */
    @Override
    public R updateTwbOrder(ErpOrderItemDto erpOrderItemDto) {
        //修改后的商品明细
        List<ErpOrderItemEntity> erpOrderItemEntityList= erpOrderItemDto.getErpOrderItemList();
        if(erpOrderItemEntityList.size()==0){
            return R.error("商品明细不能为空!");
        }
        //前台传递过来的
        ErpOrderEntity erpOrder = erpOrderItemDto.getErpOrder();
        String orderNo=erpOrder.getOrderNo();
        //计算 总金额
        BigDecimal totalMoney = erpOrderItemEntityList.stream().map(ErpOrderItemEntity::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
        erpOrder.setTotalAmount(totalMoney);
        //再查询会员信息，看是否有优惠
        Integer sellerId=erpOrder.getThirdMerchantId();
        //先查看前台是否传递sid,如果没传则需要新增会员
        Long storeMemberId= erpOrder.getStoreMemberId();
        //查询storeMember表是否存在此客户
        //如果当前客户不在storeMember
        if (null == storeMemberId) {
            StoreMemberEntity storeMember=new StoreMemberEntity();
            //添加数据到storeMember
            storeMember.setSellerId(sellerId);
            storeMember.setMerchantsType(MerchantsTypeEnum.VISIT.toCode());
            storeMember.setMerchantsSalesMan(erpOrder.getMerchantsSalesMan());
            storeMember.setAddr(erpOrder.getShipAddr());
            storeMember.setMobile(erpOrder.getShipMobile());
            storeMember.setTel(erpOrder.getShipTel());
            storeMember.setName(erpOrder.getMemberName());
            storeMember.setHangsAccountCustomer(0);
            storeMember.setMemberId(0);//写死.默认为0
            storeMember.setAutoClear(0);
            storeMember.setCreateTime(new Date());
            storeMember.setNickname(erpOrder.getShipName());
            storeMember.setMerchantsSource(1);
            storeMemberService.save(storeMember);
            erpOrder.setMemberId(0);
            erpOrder.setStoreMemberId(storeMember.getSid());
        }
        Map<String,Object> params=new HashMap<>();
        params.put("sellerId",sellerId);
        params.put("sid",erpOrder.getStoreMemberId());
        StoreMemberEntityVo storeMemberEntity= storeMemberService.getMemberBySId(params);
        //会员折扣率
        BigDecimal discountRate = storeMemberEntity.getDiscountRate();
        if(discountRate==null){
            erpOrder.setPayableAmount(totalMoney);
            erpOrder.setPmtGoods(new BigDecimal(0));
        }else{
            BigDecimal payableAmount=totalMoney.multiply(discountRate).setScale(2,BigDecimal.ROUND_HALF_UP);
            BigDecimal pmtGoods=totalMoney.subtract(payableAmount);
            erpOrder.setPayableAmount(payableAmount);
            erpOrder.setPmtGoods(pmtGoods);
        }
        //订单修改
        this.updateById(erpOrder);
        //定义删除集合
        List<ErpOrderItemEntity> delList=new ArrayList<>();
        //定义新增集合
        List<ErpOrderItemEntity> addList=new ArrayList<>();
        //定义修改集合
        List<ErpOrderItemEntity> updateList=new ArrayList<>();
        //先根据订单号，查询现在数据库商品明细
        // 商品列表
        List<ErpOrderItemEntity> erpOrderItemData = erpOrderItemService.list(
                new QueryWrapper<ErpOrderItemEntity>()
                        .eq("order_no",orderNo)
                        .eq("item_del",0)
        );

        for(int i=0;i<erpOrderItemEntityList.size();i++){
            ErpOrderItemEntity erpOrderItemEntity = erpOrderItemEntityList.get(i);
            if(erpOrderItemEntity.getEoItemId()!=null){
                updateList.add(erpOrderItemEntity);
            }else {
                erpOrderItemEntity.setOrderNo(orderNo);
                addList.add(erpOrderItemEntity);
            }
        }

        //取出所有的eoItem
        List<Long> eoItemList=updateList.stream().map(ErpOrderItemEntity::getEoItemId).collect(Collectors.toList());

        for (int i=0;i<erpOrderItemData.size();i++){
            ErpOrderItemEntity erpOrderItemEntity = erpOrderItemData.get(i);
            if(!eoItemList.contains(erpOrderItemEntity.getEoItemId())){
                erpOrderItemEntity.setItemDel(DeleteEnum.DELETE.toInt());
                delList.add(erpOrderItemEntity);
            }
        }
        if(delList.size()>0){
            erpOrderItemService.updateBatchById(delList);
        }
        if(addList.size()>0){
            erpOrderItemService.saveBatch(addList);
        }
        if(updateList.size()>0){
            erpOrderItemService.updateBatchById(updateList);
        }
        //添加操作日志
        ErpOrderLogEntity erpOrderLogEntity = new ErpOrderLogEntity();
        erpOrderLogEntity.setLogText("修改订单，删除的商品:"+JsonUtils.object2String(delList)+",修改的商品:"+JsonUtils.object2String(updateList)
                                        +",新增商品:"+JsonUtils.object2String(addList));
        erpOrderLogEntity.setOrderNo(erpOrder.getOrderNo());
        erpOrderLogEntity.setCreateTime(new Date());
        erpOrderLogEntity.setCreateName(UserUtils.getCurentUser().getUsername());
        erpOrderLogService.save(erpOrderLogEntity);
        return R.ok();
    }

    /**
     * 图文宝查询月结订单
     * @param params
     * @return
     */
    @Override
    public R queryMonthTwbOrderList(Map<String, Object> params) {
        Page<ErpOrderEntity> page = new Page<>(Integer.parseInt(params.get("page").toString()), Integer.parseInt(params.get("limit").toString()));
        Integer current= Integer.parseInt(params.get("page").toString());
        Integer limit= Integer.parseInt(params.get("limit").toString());
        if(current>0){
            current--;
        }
        params.put("current",current*limit);
        List<ErpOrderEntity> records = this.baseMapper.querytTwbPageErpOrderList(params);
        page.setRecords(records);
        Integer total=  this.baseMapper.selectTwbTotal(params);
        page.setTotal(total);
        //只根据sellerId以及挂账查询总金额,重新定义一个map封装参数
        Map<String,Object> moneyMap=new HashMap<>();
        moneyMap.put("sellerId",params.get("sellerId"));
        moneyMap.put("onCredit",1);
        List<BigDecimal> bigDecimals = this.baseMapper.queryTwbMonthMoney(moneyMap);
        BigDecimal totalMoney=BigDecimal.ZERO;
        for (int i=0;i<bigDecimals.size();i++){
            totalMoney= totalMoney.add(bigDecimals.get(i));
        }
        PageUtils pageUtils = new PageUtils(page);
        return R.ok().put("page",pageUtils).put("productionStatusEnum",JsonUtils.enumToList(ProductionStatusEnum.class))
                .put("payStatusEnum",JsonUtils.enumToList(PayStatusEnum.class))
                .put("totalMoney",totalMoney);
    }

    @Override
    public R getTwbMonthMoneyData(String orderNos) {
        if(StringUtils.isBlank(orderNos)){
            return  R.error("请至少选择一行再进行收银操作!");
        }
       String[] orderNoArray=orderNos.split(",");
        List<ErpOrderEntity> erpOrderList = this.baseMapper.selectBatchIds(Arrays.asList(orderNoArray));
        //按group属性分组
        Map<Long, List<ErpOrderEntity>> orderMap = erpOrderList.stream().collect(Collectors.groupingBy(ErpOrderEntity::getStoreMemberId));
        if(orderMap.keySet().size()>1){
            return  R.error("请确认所选订单属于同一客户!");
        }
        for (int i=0;i<erpOrderList.size();i++){
            ErpOrderEntity erpOrderEntity = erpOrderList.get(i);
            if(erpOrderEntity.getProductionStatus()!=ProductionStatusEnum.PRODUCTION_FINISH.toInt()){
                return  R.error("请检查订单<span style='color: red;'>"+erpOrderEntity.getOrderNo() +"</span>生产状态是否为生产完成,生产完成才允许进行收银!");
            }
            if(erpOrderEntity.getPayStatus()!=PayStatusEnum.NOT_PAY_0.toInt()){
                return  R.error("请检查订单<span style='color: red;'>"+erpOrderEntity.getOrderNo() +"</span>支付状态是否为未支付,未支付订单才允许进行收银!");
            }
        }
        // 应付总金额
        BigDecimal payableAmount = erpOrderList.stream().map(ErpOrderEntity::getPayableAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
        //获取客户名称
        String memberName=erpOrderList.get(0).getMemberName();
        //定义一个Map用于返回结果给前台
        Map<String,Object> moneyMap=new HashMap<>();
        moneyMap.put("payableAmount",payableAmount);
        moneyMap.put("orderCount",orderNoArray.length);
        moneyMap.put("payment","现金");//方便前台展示默认为现金收款
        moneyMap.put("memberName",memberName);
        moneyMap.put("orderNos",orderNos);
        return R.ok().put("moneyForm", moneyMap).put("payTypeData",JsonUtils.enumToList(TwbPayTypeEnum.class));

    }

    /**
     * 图文宝月结订单收款
     * @param params
     * @return
     */
    @Override
    public R saveTwbMonthMoney(Map<String, Object> params) {
        String OrderNos=params.get("orderNos").toString();
        String[] orderNoArr=OrderNos.split(",");
        BigDecimal payableAmount=new BigDecimal(params.get("payableAmount").toString());
        String payment=params.get("payment").toString();
        List<ErpOrderEntity> erpOrderList = this.baseMapper.selectBatchIds(Arrays.asList(orderNoArr));
        //原订单应该支付金额
        BigDecimal totalPayableAmount = erpOrderList.stream().map(ErpOrderEntity::getPayableAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal discount = totalPayableAmount.subtract(payableAmount);
        int compare = discount.compareTo(BigDecimal.ZERO);
        String orderNoMax = null;
        if (compare != 0) {
            // 客户填写调价金额不为0，从待付款订单号中找出应付金额最大值，
            // 并记录调价优惠信息，其他应收金额照常收取
            Optional<ErpOrderEntity> max = erpOrderList.stream().max((x, y) -> x.getPayableAmount().compareTo(y.getPayableAmount()));
            ErpOrderEntity erpOrderMax = max.get();
            orderNoMax = erpOrderMax.getOrderNo();
        }
        Map<String, Object> updateMap = new HashMap<>();
        String paymentTime = DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss");
        //批量添加日志
        List<ErpOrderLogEntity> erpOrderLogList=new ArrayList<>();
        for (ErpOrderEntity erpOrder : erpOrderList) {
            /* 更新用户支付记录 */
            String orderNo = erpOrder.getOrderNo();
            BigDecimal pAmount = erpOrder.getPayableAmount();
            String paymentsId = UserPaymentUtils.getPaymentsId();
            boolean repeat = true;
            do {
                UserPaymentEntity upe = userPaymentService.getById(paymentsId);
                if (upe == null) {
                    repeat = false;
                }
            } while (repeat);
            UserPaymentEntity userPayment = new UserPaymentEntity();
            userPayment.setPaymentId(paymentsId);
            userPayment.setMoney(pAmount);
            userPayment.setCurMoney(pAmount);
            userPayment.setUserId(erpOrder.getMemberId().toString());
            userPayment.setStatus("succ");
            userPayment.setTPayed(new Date());
            userPayment.setSource("erp");
            userPayment.setPayAppId(EnumUtil.getEnumByDesc(TwbPayTypeEnum.class,payment).toCode());
            userPayment.setPayType("offline");
            userPayment.setOpId(UserUtils.getCurentUser().getUserId().toString());
            userPaymentService.save(userPayment);

            UserPaymentBillEntity userPaymentBill = new UserPaymentBillEntity();
            userPaymentBill.setRelId(Long.valueOf(orderNo));
            userPaymentBill.setBillType("payments");
            userPaymentBill.setPayObject("order");
            userPaymentBill.setBillId(userPayment.getPaymentId());
            userPaymentBill.setMoney(userPayment.getMoney());
            userPaymentBillService.save(userPaymentBill);

            /* 更新订单状态信息 */
            if (orderNoMax != null && StringUtils.equals(orderNoMax, orderNo)) {
                pAmount = pAmount.add(discount);
                updateMap.put("discount", discount);
            }
            updateMap.put("paymentId", paymentsId);
            updateMap.put("payment", payment);
            updateMap.put("shipStatus",ShipStatusEnum.shipped.toCode());
            updateMap.put("receivedStatus",ReceivedStatusEnum.RECEIVED.toInt());
            updateMap.put("payableAmount", pAmount);
            updateMap.put("payed", pAmount);
            if(erpOrder.getSendType()==1){
                if(erpOrder.getReceivedTime()==null){
                    updateMap.put("receivedTime",new Date());
                }
                if(erpOrder.getSendTime()==null){
                    updateMap.put("sendTime",new Date());
                }
                if(erpOrder.getDeliveryTime()==null){
                    updateMap.put("deliveryTime",new Date());
                }
                if(erpOrder.getFinishTime()==null){
                    updateMap.put("finishTime",new Date());
                }
            }
            updateMap.put("payStatus", PayStatusEnum.ALREADY_PAY_1.toCode());
            updateMap.put("paymentTime", paymentTime);
            updateMap.put("productionStatus", ProductionStatusEnum.FINISH.toInt());
            this.baseMapper.updateByMap(updateMap, orderNo);

            ErpOrderLogEntity erpOrderLog = new ErpOrderLogEntity();
            erpOrderLog.setOrderNo(orderNo);
            erpOrderLog.setCreateName(UserUtils.getCurentUser().getUsername());
            erpOrderLog.setCreateTime(new Date());
            erpOrderLog.setCreateBy(UserUtils.getCurentUser().getSellerId().toString());
            erpOrderLog.setLogText("门店月结订单收款");
            erpOrderLogList.add(erpOrderLog);
        }
        erpOrderLogService.saveBatch(erpOrderLogList);

        return R.ok();
    }

    /**
     * 小程序查询订单列表
     * @param twbOrderParamDto
     * @return
     */
    @Override
    public R queryPageForTwbOrderList(TwbOrderParamDto twbOrderParamDto) {
        //定义map
        Map<String,Object> map=new HashMap<>();
        if(twbOrderParamDto.getPage()>0){
           Integer current=(twbOrderParamDto.getPage()-1)*twbOrderParamDto.getSize();
            map.put("current",current);
        }else{
            map.put("current",0);
        }
        map.put("size",twbOrderParamDto.getSize());
        map.put("sellerId",twbOrderParamDto.getSellerId());
        if(twbOrderParamDto.getProductionStatus()!=null){
            map.put("productionStatus",twbOrderParamDto.getProductionStatus());
        }
        if(twbOrderParamDto.getPayStatus()!=null){
            map.put("payStatus",twbOrderParamDto.getPayStatus());
        }
        List<TwbOrderListDto> twbOrderList= this.baseMapper.queryPageForTwbOrderList(map);
        Long count = this.baseMapper.getCountForTwbOrderList(map);
        for (int i=0;i<twbOrderList.size();i++){
            twbOrderList.get(i).setTotal(count);
        }
        return R.apiOk(twbOrderList);
    }

    /**
     * 图文宝手机端根据订单号查询订单信息
     * @param orderNo
     * @return
     */
    @Override
    public R getTwbOrderInfo(String orderNo) {
        //根据订单号查询订单
        ErpOrderEntity erpOrderEntity = this.getById(orderNo);
        //再查询商品信息
        List<ErpOrderItemEntity> erpOrderItemEntityList=erpOrderItemService.list(
                new QueryWrapper<ErpOrderItemEntity>().eq("item_del",DeleteEnum.NOT_DELETE.toInt()).eq("order_no",orderNo));
        if(erpOrderEntity.getOrderSource()==1){
            //再根据商品查询附件
            for (int i=0;i<erpOrderItemEntityList.size();i++){
                ErpOrderItemEntity erpOrderItemEntity = erpOrderItemEntityList.get(i);
                if(erpOrderItemEntity.getOriginalItemId()!=null){
                List<UserAccessoryEntity>  userAccessoryEntityList=userAccessoryService.getAccessoryByItemId(erpOrderItemEntity.getOriginalItemId());
                    erpOrderItemEntity.setUserAccessoryEntitieList(userAccessoryEntityList);
                }
            }
        }
        TwbOrderDetailDto twbOrderDetailDto=new TwbOrderDetailDto();
        //查询发票信息,如果为紫云网订单，则还需要查询发票信息
        if(erpOrderEntity.getOrderSource()==OrderSourceEnum.ZIYUN.toInt()){
                OrderTaxEntity orderTax = orderTaxService.getById(erpOrderEntity.getOrderNo());
                twbOrderDetailDto.setOrderTaxEntity(orderTax);
        }
        twbOrderDetailDto.setErpOrderEntity(erpOrderEntity);
        twbOrderDetailDto.setErpOrderItemList(erpOrderItemEntityList);
        return R.apiOk(twbOrderDetailDto);
    }

    /**
     * 图文宝手机端订单审核
     * @param orderNo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R audit(String orderNo,SysUserEntity sysUserEntity) {
         //判断是否所有订单状态是否均为待审核
        ErpOrderEntity erpOrderEntity=this.getById(orderNo);
        if(erpOrderEntity.getProductionStatus()!=ProductionStatusEnum.UN_AUDITED.toInt()){
            return R.apiError(1000,"请检查所选订单生产状态是否为待审核状态!只有待审核才能进行审核操作");
        }
        //查询是否是自营分配的，这类订单无支付信息
        Boolean ziyunAllot = this.isZiyunAllot(orderNo);
        //未支付订单。且不属于自营分配，不允许审核
        if(!erpOrderEntity.getPayStatus().toString().equals(PayStatusEnum.ALREADY_PAY_1.toCode())&&!ziyunAllot){
            return R.apiError(1001,"请先确认订单"+orderNo+"是否已经支付!未支付订单不允许进行审核操作!");
        }
        Map<String,Object> map=new HashMap<>();
        map.put("auditName",sysUserEntity.getUsername());
        map.put("auditTime",new Date());
        map.put("productionStatus",ProductionStatusEnum.IN_PRODUCTION.toInt());
        this.baseMapper.updateByMap(map, orderNo);
        List<String> orderNoList=new ArrayList<>();
        orderNoList.add(orderNo);
        //先获取所有订单号,如果是分配过来的，需要将生产单状态改为生产中
        List<ErpOrderProductionEntity> productionList=  erpOrderProductionService.selectProductionListByOrderNos(orderNoList);
        for (int i=0;i<productionList.size();i++){
            productionList.get(i).setProductionStatus(2); //1.待生产,2.生产中,3.生产完成,4.取消
        }
        if(productionList.size()>0){
            erpOrderProductionService.updateBatchById(productionList);
        }
        //添加订单日志
        ErpOrderLogEntity erpOrderLogEntity=new ErpOrderLogEntity();
        erpOrderLogEntity.setOrderNo(orderNo);
        erpOrderLogEntity.setCreateBy(sysUserEntity.getUserId().toString());
        erpOrderLogEntity.setCreateName(sysUserEntity.getUsername());
        erpOrderLogEntity.setCreateTime(new Date());
        erpOrderLogEntity.setLogText("手机端审核操作");
        erpOrderLogService.save(erpOrderLogEntity);
        return R.apiOk(null);
    }
    /**
     * 图文宝手机端订单生产完成
     * @param orderNo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R productFinish(String orderNo, SysUserEntity curentUser) {
        ErpOrderEntity erpOrderEntity = this.getById(orderNo);
        //判断是否所有订单状态是否均为生产中
        if (erpOrderEntity.getProductionStatus() != ProductionStatusEnum.IN_PRODUCTION.toInt()) {
            return R.apiError(1000,"请检查所选订单生产状态是否为生产中状态!只有生产中订单才能进行订单完成操作!");
        }
        //查询是否是自营分配的，这类订单无支付信息
        Boolean ziyunAllot = this.isZiyunAllot(orderNo);
        //如果是商城订单，并且不是自营分配的，未支付订单不允许进行生产完成操作
        if (!erpOrderEntity.getPayStatus().toString().equals(PayStatusEnum.ALREADY_PAY_1.toCode()) && erpOrderEntity.getOrderSource() == OrderSourceEnum.ZIYUN.toInt() && !ziyunAllot) {
            return R.apiError(1001,"请先确认订单" + orderNo+"是否已经支付!未支付订单不允许进行生产完成操作!");
        }
        //查询支付表，如果没有支付成功信息，也提示不允许进行操作！
        if (erpOrderEntity.getOrderSource() == OrderSourceEnum.ZIYUN.toInt()) {
            //如果不是自营分配，再查询支付信息
            if (!ziyunAllot) {
                //查询支付表，看是否有支付成功信息
                UserPaymentEntity userPayment = userPaymentService.getPaySuccLastEntityByOrderNo(erpOrderEntity.getOrderNo());
                if (userPayment == null) {
                    return R.apiError(1001,"请先确认订单" + orderNo + "是否已经支付!未支付订单不允许进行生产完成操作!");
                }
            }
        }
        //首先判断是否为分配过来订单
        int count = erpOrderAllotRelevanceService.count(new QueryWrapper<ErpOrderAllotRelevanceEntity>().eq("order_allot_no", erpOrderEntity.getOrderNo())
                .eq("del", DeleteEnum.NOT_DELETE.toInt()));
        //如果是分配过来订单，并且是自提，则改变发货状态，生产状态为生产完成
        erpOrderEntity.setFinishTime(new Date());
        if (erpOrderEntity.getOrderSource() == OrderSourceEnum.ZIYUN.toInt() && erpOrderEntity.getSendType() == SendTypeEnum.PICK_UP.toInt() && count > 0) {
            erpOrderEntity.setProductionStatus(ProductionStatusEnum.PRODUCTION_FINISH.toInt());
            erpOrderEntity.setShipStatus(Integer.valueOf(ShipStatusEnum.shipped.toCode()));
        } else if (erpOrderEntity.getOrderSource() == OrderSourceEnum.ZIYUN.toInt() && erpOrderEntity.getSendType() == SendTypeEnum.PICK_UP.toInt() && count == 0) {
            //如果是本身商城下的订单，并且是自提，生产完成就是已完成并发货
            erpOrderEntity.setProductionStatus(ProductionStatusEnum.FINISH.toInt());
            erpOrderEntity.setShipStatus(Integer.valueOf(ShipStatusEnum.shipped.toCode()));
            erpOrderEntity.setReceivedStatus(ReceivedStatusEnum.RECEIVED.toInt());
            erpOrderEntity.setReceivedTime(new Date());
            erpOrderEntity.setSendTime(new Date());
            erpOrderEntity.setDeliveryTime(new Date());
        } else {
            erpOrderEntity.setProductionStatus(ProductionStatusEnum.PRODUCTION_FINISH.toInt());
        }
        //批量更改状态，erpOrder
        this.updateById(erpOrderEntity);
        //根据订单号去order_info表中查询，查询出来的均为商城订单或者分配过来订单
        OrderInfoEntity orderInfo= orderInfoService.getById(orderNo);
        //定义一个集合，用于修改orderInfo表中信息
        List<OrderInfoEntity> updateOrderInfoList=new ArrayList<>();
        //定义一个集合，用于修改erp_order_production表中信息
        List<ErpOrderProductionEntity> erpOrderProductionEntityList=new ArrayList<>();
        if(orderInfo!=null){
            //首先判断是否为分配过来订单
            int releCount = erpOrderAllotRelevanceService.count(new QueryWrapper<ErpOrderAllotRelevanceEntity>().eq("order_allot_no", orderInfo.getOrderId())
                    .eq("del", DeleteEnum.NOT_DELETE.toInt()));
            //如果不是分配，并且自提，
            if(orderInfo.getPickUp()&&!orderInfo.getSource().equals("erp")&&releCount==0){
                orderInfo.setStatus(OrderInfoStatusEnum.FINISH.toCode());
                orderInfo.setShipStatus(ShipStatusEnum.shipped.toCode());
                orderInfo.setReceivedStatus(true);
                orderInfo.setReceivedTime(new Date());
                orderInfo.setShipTime("自取");
            }
            //如果不是分配,非自提,不修改orderInfo信息
            if(!orderInfo.getPickUp()&&(!orderInfo.getSource().equals("erp"))&&releCount==0){

            }
            //如果是分配,自提,只更改发货状态和生产状态
            if(orderInfo.getPickUp()&&(!orderInfo.getSource().equals("erp"))&&releCount>0){
                orderInfo.setShipStatus(ShipStatusEnum.shipped.toCode());
                //查询生产单信息
                List<ErpOrderProductionEntity> productionList = erpOrderProductionService.list(new QueryWrapper<ErpOrderProductionEntity>().eq("production_order", orderInfo.getOrderId())
                        .notIn("production_status", OrderProductionStatusEnum.CANCLE.toInt()).eq("del", 0));
                for (int j=0;j<productionList.size();j++){
                    ErpOrderProductionEntity erpOrderProductionEntity = productionList.get(j);
                    erpOrderProductionEntity.setProductionStatus(3); //1.待生产,2.生产中,3.生产完成,4.取消
                    erpOrderProductionEntityList.add(erpOrderProductionEntity);
                }
            }
            //如果是分配，不自提,只修改生产单信息
            if(!orderInfo.getPickUp()&&(!orderInfo.getSource().equals("erp"))&&releCount>0){
                //查询生产单信息
                List<ErpOrderProductionEntity> productionList = erpOrderProductionService.list(new QueryWrapper<ErpOrderProductionEntity>().eq("production_order", orderInfo.getOrderId())
                        .eq("production_status", OrderProductionStatusEnum.CANCLE.toInt()).eq("del", 0));
                for (int j=0;j<productionList.size();j++){
                    ErpOrderProductionEntity erpOrderProductionEntity = productionList.get(j);
                    erpOrderProductionEntity.setProductionStatus(3); //1.待生产,2.生产中,3.生产完成,4.取消
                    erpOrderProductionEntityList.add(erpOrderProductionEntity);
                }
            }
            orderInfoService.updateById(orderInfo);
            if(erpOrderProductionEntityList.size()>0){
                erpOrderProductionService.updateBatchById(erpOrderProductionEntityList);
            }
        }
        //添加订单日志
            ErpOrderLogEntity erpOrderLogEntity=new ErpOrderLogEntity();
            erpOrderLogEntity.setOrderNo(orderNo);
            erpOrderLogEntity.setCreateBy(curentUser.getUserId().toString());
            erpOrderLogEntity.setCreateName(curentUser.getUsername());
            erpOrderLogEntity.setCreateTime(new Date());
            erpOrderLogEntity.setLogText("手机端生产完成操作");
            erpOrderLogService.save(erpOrderLogEntity);
            return R.apiOk(null);
        }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R batchSweepCodeBegin(Map<String, Object> params) {
        String payName = params.get("payName").toString();
        BigDecimal money = new BigDecimal(params.get("money").toString());
        String orderNos = params.get("orderNos").toString();
        if (!StringUtils.isNotBlank(payName)) {
            return R.error("获取支付名称错误，收银失败!");
        }
        if (!StringUtils.isNotBlank(orderNos)) {
            return R.error("获取订单相关数据错误，收银失败!");
        }
        List<String> orderNoList = Arrays.asList(orderNos.split(","));
        //查询订单
        List<ErpOrderEntity> orderList=this.list(new QueryWrapper<ErpOrderEntity>().in("order_no",orderNoList));

        //添加支付单信息
        UserPaymentEntity userPayment = new UserPaymentEntity();
        // 收款单号
        String paymentId = null;
        // 判断收款单号是否重复
        boolean repeat = true;
        do {
            paymentId = UserPaymentUtils.getPaymentsId();
            List<UserPaymentEntity> countList = userPaymentService.list(new QueryWrapper<UserPaymentEntity>().eq("payment_id", paymentId));
            if (countList == null || countList.size() <= 0) {
                repeat = false;
            }
        } while (repeat);

        userPayment.setPaymentId(paymentId);
        userPayment.setMoney(money);
        userPayment.setCurMoney(money);
        userPayment.setUserId(orderList.get(0).getMemberId().toString());
        userPayment.setStatus("ready");
        userPayment.setPayName(payName);
        userPayment.setTPayed(new Date());
        userPayment.setPayType("online");//线下支付
        userPayment.setTBegin(new Date());
        userPayment.setPayAppId(EnumUtil.getEnumByDesc(PayTypeEnum.class, payName).toCode());
        //用户支付记录表;
        userPaymentService.save(userPayment);

        List<UserPaymentBillEntity> upbList=new ArrayList<>();
        List<BatchOrderPaymentEntity> batchOrderPaymentList=new ArrayList<>();
        for (int i=0;i<orderList.size();i++){
            ErpOrderEntity erpOrder=orderList.get(i);
            // 订单，支付单关联信息
            UserPaymentBillEntity userPaymentBill = new UserPaymentBillEntity();
            userPaymentBill.setRelId(Long.valueOf(erpOrder.getOrderNo()));
            userPaymentBill.setBillId(userPayment.getPaymentId());
            userPaymentBill.setPayObject(PayObjectEnum.ORDER.toCode());
            userPaymentBill.setBillType(BillTypeEnum.PAYMENTS.toCode());
            //订单已支付金额
            BigDecimal payed=erpOrder.getPayed()==null?BigDecimal.ZERO:erpOrder.getPayed();
            BigDecimal payMoney=erpOrder.getPayableAmount().subtract(payed);
            userPaymentBill.setMoney(payMoney);
            upbList.add(userPaymentBill);
            BatchOrderPaymentEntity batchOrderPaymentEntity=new BatchOrderPaymentEntity();
            batchOrderPaymentEntity.setStatus("ready");
            batchOrderPaymentEntity.setDel(false);
            batchOrderPaymentEntity.setOrderNo(erpOrder.getOrderNo());
            batchOrderPaymentEntity.setPaymentId(paymentId);
            batchOrderPaymentList.add(batchOrderPaymentEntity);
        }
        if(upbList.size()>0){
            userPaymentBillService.saveBatch(upbList);
        }
        //将订单以及流水信息写入到batch_order_payment
        if(batchOrderPaymentList.size()>0){
           batchOrderPaymentService.saveBatch(batchOrderPaymentList);
        }
        // 返回 支付金额 分， 支付流水 右侧补空格 长度50位
        // 拼接银联请求字符串
        StringBuffer sBuffer = new StringBuffer("02"); //应用类型  02-无硬件POS通
        sBuffer.append("0000000000000000");// POS机号 + 员工号
        sBuffer.append("00");//交易类型  00－消费
        sBuffer.append(String.format("%012d", money.multiply(BigDecimal.valueOf(100L)).intValue())); // 金额 无小数点"."，单位为分，不足时12位左补0
        sBuffer.append(DateUtils.format(new Date(), "yyyyMMdd"));// 交易日期 YYYMMDD
        sBuffer.append("000000000000");//原交易参考号
        sBuffer.append("000000");//凭证号
        sBuffer.append("ERP");//LRC校验
        //sBuffer.append(params.get("serialCode"));
        sBuffer.append(String.format("%1$-50s",params.get("serialCode"))); // 串码
        sBuffer.append(String.format("%1$-50s",paymentId));// 商户订单号
        sBuffer.append(String.format("%1$-50s",paymentId));// 商户订单号
        return R.ok().put("DUmsocx1",sBuffer).put("paymentId",paymentId);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public R sweepCodeBegin(Map<String, Object> params) {
        String payName = params.get("payName").toString();
        String memberId = params.get("memberId").toString();
        BigDecimal money = new BigDecimal(params.get("money").toString());
        String orderNo = params.get("orderNo").toString();
        if (!StringUtils.isNotBlank(payName)) {
            return R.error("获取支付名称错误，收银失败!");
        }
        if (!StringUtils.isNotBlank(orderNo)) {
            return R.error("获取订单相关数据错误，收银失败!");
        }
        //添加支付单信息
        UserPaymentEntity userPayment = new UserPaymentEntity();
        // 收款单号
        String paymentId = null;
        // 判断收款单号是否重复
        boolean repeat = true;
        do {
            paymentId = UserPaymentUtils.getPaymentsId();
            List<UserPaymentEntity> countList = userPaymentService.list(new QueryWrapper<UserPaymentEntity>().eq("payment_id", paymentId));
            if (countList == null || countList.size() <= 0) {
                repeat = false;
            }
        } while (repeat);
        userPayment.setPaymentId(paymentId);
        userPayment.setMoney(money);
        userPayment.setCurMoney(money);
        userPayment.setUserId(memberId);
        userPayment.setStatus("ready");
        userPayment.setPayName(payName);
        userPayment.setTPayed(new Date());
        userPayment.setPayType("online");//线下支付
        userPayment.setTBegin(new Date());
        userPayment.setPayAppId(EnumUtil.getEnumByDesc(PayTypeEnum.class, payName).toCode());
        //用户支付记录表;
        userPaymentService.save(userPayment);
        // 订单，支付单关联信息
        UserPaymentBillEntity userPaymentBill = new UserPaymentBillEntity();
        userPaymentBill.setRelId(Long.valueOf(orderNo));
        userPaymentBill.setBillId(userPayment.getPaymentId());
        userPaymentBill.setPayObject(PayObjectEnum.ORDER.toCode());
        userPaymentBill.setBillType(BillTypeEnum.PAYMENTS.toCode());
        userPaymentBill.setMoney(userPayment.getMoney());
        userPaymentBillService.save(userPaymentBill);

        // 返回 支付金额 分， 支付流水 右侧补空格 长度50位

        // 拼接银联请求字符串
        StringBuffer sBuffer = new StringBuffer("02"); //应用类型  02-无硬件POS通
        sBuffer.append("0000000000000000");// POS机号 + 员工号
        sBuffer.append("00");//交易类型  00－消费
        sBuffer.append(String.format("%012d", money.multiply(BigDecimal.valueOf(100L)).intValue())); // 金额 无小数点"."，单位为分，不足时12位左补0
        sBuffer.append(DateUtils.format(new Date(), "yyyyMMdd"));// 交易日期 YYYMMDD
        sBuffer.append("000000000000");//原交易参考号
        sBuffer.append("000000");//凭证号
        sBuffer.append("ERP");//LRC校验
        //sBuffer.append(params.get("serialCode"));
        sBuffer.append(String.format("%1$-50s",params.get("serialCode"))); // 串码
        sBuffer.append(String.format("%1$-50s",paymentId));// 商户订单号
        sBuffer.append(String.format("%1$-50s",paymentId));// 商户订单号

        return R.ok().put("DUmsocx1",sBuffer).put("paymentId",paymentId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R sweepCodeCallBack(Map<String, Object> params) {
        // 先处理支付订单信息,将支付状态改为成功
        String paymentId = params.get("paymentId").toString();
        String sweepCodeData = params.get("sweepCodeData").toString();
        UserPaymentEntity userPaymentEntity = userPaymentService.getById(paymentId);
        if (userPaymentEntity == null){
            throw new RRException("支付单号异常!");
        }
      /*  String payType="";
        //截取支付方式
        try {
            String temp =  new String(sweepCodeData.getBytes(),"gbk");
            payType = temp.substring(506,507);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }*/
        //先写入响应码
        userPaymentEntity.setPayResponseData(sweepCodeData);
        userPaymentService.writePayResponseData(userPaymentEntity);

        if(!sweepCodeData.substring(0,2).equals("00")){
            logger.info("扫码支付接收到服务器发送的数据:"+sweepCodeData);
            throw new RRException("支付失败!响应码为:"+sweepCodeData);
        }


        /*String payCode = null;
        String payName = null;
        if (payType.equals("0")){
            payCode = "sweepcodealipay";
            payName = "扫码支付宝";
        }else if (payType.equals("1")){
            payCode = "sweepcodeweixin";
            payName = "扫码微信";
        }else if (payType.equals("2")){
            payCode = "sweepcodeunion";
            payName = "扫码银联";
        }else if (payType.equals("3")){
            payCode = "sweepcodeother";
            payName = "扫码其它";
        }else {
            throw new RRException("获取支付方式异常!");
        }*/
        params.put("payName","扫码支付");
        userPaymentEntity.setStatus("succ");
        userPaymentEntity.setTPayed(new Date());
        //userPaymentEntity.setPayAppId(payCode);
        userPaymentService.updateById(userPaymentEntity);
        // 处理业务信息
        this.receiveMoneyByCode(params);
        return R.ok();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R batchSweepCodeCallBack(Map<String, Object> params) {
        // 先处理支付订单信息,将支付状态改为成功
        String paymentId = params.get("paymentId").toString();
        String sweepCodeData = params.get("sweepCodeData").toString();
        UserPaymentEntity userPaymentEntity = userPaymentService.getById(paymentId);
        if (userPaymentEntity == null){
            throw new RRException("支付单号异常!");
        }
        //先写入响应码
        userPaymentEntity.setPayResponseData(sweepCodeData);
        userPaymentService.writePayResponseData(userPaymentEntity);

        if(!sweepCodeData.substring(0,2).equals("00")){
            logger.info("扫码支付接收到服务器发送的数据:"+sweepCodeData);
            throw new RRException("支付失败!响应码为:"+sweepCodeData);
        }
        params.put("payName","扫码支付");
        userPaymentEntity.setStatus("succ");
        userPaymentEntity.setTPayed(new Date());
        userPaymentService.updateById(userPaymentEntity);
        //修改batch_order_payment表中信息
       List<BatchOrderPaymentEntity> batchOrderPaymentList= batchOrderPaymentService.list(
               new QueryWrapper<BatchOrderPaymentEntity>().eq("payment_id",paymentId).eq("status","ready"));
       for (int i=0;i<batchOrderPaymentList.size();i++){
           BatchOrderPaymentEntity batchOrderPaymentEntity = batchOrderPaymentList.get(i);
           batchOrderPaymentEntity.setStatus("succ");
           batchOrderPaymentEntity.setPaymentTime(new Date());
       }
        if(batchOrderPaymentList.size()>0){
            batchOrderPaymentService.updateBatchById(batchOrderPaymentList);
        }
        // 处理业务信息
        this.bacthReceiveMoneyByCode(params);
        return R.ok();
    }



    @Override
    public R getOrderMessage(OrderMessageParamDto orderMessageParamDto, Long mallUserId) {
        logger.info("================= order message api param：" + JsonUtils.object2String(orderMessageParamDto) + "," + mallUserId);
        OrderResult<PageResult<OrderMessageVO>> pageResultOrderResult = microOrderService.listOrderMessage(mallUserId, orderMessageParamDto);
        int code = pageResultOrderResult.getCode();
        if (code != 1) {
            String message = pageResultOrderResult.getMessage();
            if (code == 999) {
                logger.error("================= order message api error：" + message);
                message = "订单消息服务异常";
            }
            return R.apiError(500, message);
        }
        PageResult<OrderMessageVO> data = pageResultOrderResult.getData();
        return R.apiOk(data);
    }

    /**
     * 图文宝添加供应商;
     * @param orderSupplierDto
     * @param userId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R twbSuppSave(OrderSupplierDto orderSupplierDto, Long userId) {
        OrderInfoEntity orderInfoEntity = orderInfoService.getById(orderSupplierDto.getOrderId());
        Integer eoItemId = orderSupplierDto.getEoItemId();
        //根据eoItemId查询出ogriginalItemId
        ErpOrderItemEntity orderItemEntity = erpOrderItemService.getById(eoItemId);
        //查询生产成本已经录入完成,则不允许添加外协
        ErpOrderEntity erpOrderEntity = this.getById(orderItemEntity.getOrderNo());
        if (erpOrderEntity.getCommissionStatus() != CommissionStatusEnum.NOTENTERED.toInt()) {
            return R.error("生产成本录入完成订单不允许添加外协!");
        }
        Integer originalItemId = orderItemEntity.getOriginalItemId();
        ErpOrderProductionEntity erpOrderProduction = new ErpOrderProductionEntity();
        erpOrderProduction.setOrderNo(orderSupplierDto.getOrderId());
        erpOrderProduction.setErpItemId(orderSupplierDto.getEoItemId().toString());
        if(null != originalItemId){
            erpOrderProduction.setOrderItemId(originalItemId.toString());
        }
        erpOrderProduction.setAttributeName(orderSupplierDto.getAttributeName());
        erpOrderProduction.setCost(orderSupplierDto.getCost());
        if (orderSupplierDto.getCost().compareTo(new BigDecimal(0)) > 0) {
            erpOrderProduction.setCostStatus(true);
        } else {
            erpOrderProduction.setCostStatus(false);
        }
        //添加供应商类型; 5:图文宝添加供应商;
        if (null == orderSupplierDto.getSupplierId()){
            erpOrderProduction.setProducer(5);
        }else {
            erpOrderProduction.setProducer(orderSupplierDto.getSupplierId());
        }
        erpOrderProduction.setCsRemark(orderSupplierDto.getCsRemark());
        erpOrderProduction.setProductionStatus(OrderProductionStatusEnum.PRODUCING.toInt());
        erpOrderProduction.setProducerType(ProducerTypeEnum.ZIYUN_SUPPLIER.toInt());
        //外协从erp_supplier_offline表中查询
       // ErpSupplierOfflineEntity erpSupplierOfflineEntity = erpSupplierOfflineService.selectByProduId(orderSupplierDto.getSupplierId());
//        if (erpSupplierOfflineEntity != null) {
//            erpOrderProduction.setProducerName(erpSupplierOfflineEntity.getSupplierName());
//        }
        erpOrderProduction.setProducerName(orderSupplierDto.getSupplierName());
        erpOrderProduction.setCreateName(userId.toString());
        erpOrderProduction.setAllotType(AllotTypeEnum.GOODS.toCode());
        erpOrderProductionService.save(erpOrderProduction);

        return R.ok();
    }

    /**
     * 图文宝删除供应商分配信息;
     * @param productionId
     * @return
     */
    @Override
    public R twbdeleteAllotItem(Integer productionId) {
        //通过id获取到对应的商品信息;
        ErpOrderProductionEntity erpOrderProduction = erpOrderProductionService.getById(productionId);
        //通过商品信息获取到产品的类型;
        Integer producerType = erpOrderProduction.getProducerType();
        //获取到对应的订单号
        String orderNo = erpOrderProduction.getOrderNo();
        String erpItemId = erpOrderProduction.getErpItemId();
        Integer producer = erpOrderProduction.getProducer();
        Integer productionStatus = erpOrderProduction.getProductionStatus();
        String productionOrder = erpOrderProduction.getProductionOrder();
        //如果是外协商,判断当前财务审核状态
        Integer financeStatus = erpOrderProduction.getFinanceStatus();
        if (financeStatus == FinanceStatusEnum.UN_AUDITED.toInt()) {
            //为待审核，则允许删除生产单,4为取消
            erpOrderProduction.setProductionStatus(ProductionStatus.PRODUCTION_STATUS_4.toInt());
            erpOrderProduction.setDel(DeleteEnum.DELETE.toInt());
            erpOrderProduction.setUpdateName(UserUtils.getCurentUser().getUsername());
            erpOrderProduction.setUpdateTime(new Date());
            erpOrderProductionService.updateById(erpOrderProduction);
            //添加操作日志
            ErpOrderLogEntity erpOrderLogEntity = new ErpOrderLogEntity();
            erpOrderLogEntity.setLogText("删除分配信息，分配productionId:" + productionId);
            erpOrderLogEntity.setOrderNo(orderNo);
            erpOrderLogEntity.setCreateTime(new Date());
            erpOrderLogEntity.setCreateName(UserUtils.getCurentUser().getUsername());
            erpOrderLogService.save(erpOrderLogEntity);
        }else if(financeStatus == FinanceStatusEnum.PAYD.toInt()) {
                return R.error("分配订单已支付，无法删除");
        }
        return R.ok();
    }

    //判断是否为紫云网分配过来的订单，紫云网分配过来的，则订单无需支付也可操作(包括门店分配的也是)
    // true为自营分配，false为非自营分配
    public  Boolean isZiyunAllot(String orderNo){
        ErpOrderEntity erpOrderEntity = this.getById(orderNo);
        //首先判断是否是分配的，不是分配的，则必须要支付
        //首先判断是否为分配过来订单
        int count = erpOrderAllotRelevanceService.count(new QueryWrapper<ErpOrderAllotRelevanceEntity>().eq("order_allot_no", orderNo)
                .eq("del", DeleteEnum.NOT_DELETE.toInt()));
        if(count==0){
            return false;
        }
       Integer self= sellerInfoService.getSelfByOrderNo(orderNo);
       if(self==null||self==0){
           return false;
       }else {
           return true;
       }
    }

    //将addon属性解析成集合
    private List<ProductInfoParam> addon2ProductInfoParamList(String addon){
        List<ProductInfoParam> productInfoParamList=JsonUtils.string2Collection(addon,List.class,ProductInfoParam.class);
        for (int i = 0; i <productInfoParamList.size() ; i++) {
            ProductInfoParam productInfoParam=productInfoParamList.get(i);
            StringBuilder basicStrSb=new StringBuilder();
            for (Object value : productInfoParam.getBasicParam().values()) {
                basicStrSb.append(value).append(" ");
            }
            productInfoParam.setBasicParamStr(basicStrSb.toString());
            //处理数据
            String craft=JsonUtils.map2String(productInfoParam.getCraftParam());
            craft=craft.replaceAll("\"", "").replace("{","").replace("}","");
            productInfoParam.setCraftParamStr(craft);
        }
        return productInfoParamList;
    }

}